Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

259
Views
Connect the authentication service with the AuthGuard (simple issue)

I guess it's quite simple issue, but unfortunately I don't really know how to deal with it.

I'm trying to connect my UserAuthenticationService service with the ActivationGuard.

UserAuthenticationService.ts:

import {Injectable} from '@angular/core';
import {Http} from '@angular/http';

@Injectable()
export class UserAuthenticationService {
    isUserAuthenticated: boolean = false;
    username: string;

    constructor(private http: Http) {
    }

    authentication() {
        this.http.get(`http://localhost/api/auth/isLogged/${this.username}`)
            .subscribe(res => { //^^returns true or false, depending if the user is logged or not
                    this.isUserAuthenticated = res.json();
                },   
                err => {
                    console.error('An error occured.' + err);
                });
    }


}

ActivationGuard.ts

import {Injectable} from '@angular/core';
import {Router, RouterStateSnapshot, ActivatedRouteSnapshot} from '@angular/router';
import {Observable} from 'rxjs/Observable';
import {UserAuthenticationService} from './UserAuthenticationService';

interface CanActivate {
    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean>|Promise<boolean>|boolean
}

@Injectable()
export class WorksheetAccessGuard implements CanActivate {

    constructor(private router: Router, private userService: UserAuthenticationService) {
    }

    public canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {

        if (this.userService) {
            this.router.navigate(['/']);
            return false;
        }
        return true;
    }
}

Note

It works great, if I just use localStorage to store the information if the user is logged or not:

public canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {

    if (!localStorage.getItem('currentUser')) {
        this.router.navigate(['/']);
        return false;
    }
    return true;
}

But how can I connect the service with the guard? Looking forward for any kind of help. Thank you in advance.

If you need any more information, please let me know and I will edit my post.

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Call authentication() method of UserAuthenticationService either in constructor or On ngOnit then it sets the isUserAuthenticated variable and use that in the ActivationGuard.ts

UserAuthenticationService.ts:

import {Injectable} from '@angular/core';
import {Http} from '@angular/http';

@Injectable()
export class UserAuthenticationService {
    isUserAuthenticated: boolean = false;
    username: string;

    constructor(private http: Http) {
    this.authentication();
    }

    authentication() {
        this.http.get(`http://localhost/api/auth/isLogged/${this.username}`)
            .subscribe(res => { //^^returns true or false, depending if the user is logged or not
                    this.isUserAuthenticated = res.json();
                },   
                err => {
                    console.error('An error occured.' + err);
                });
    }


}  

ActivationGuard.ts

 @Injectable()
export class WorksheetAccessGuard implements CanActivate {

    constructor(private router: Router, private userService: UserAuthenticationService) {
    }

    public canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {

        if (this.userService.isUserAuthenticated) {
            this.router.navigate(['/']);
            return false;
        }
        return true;
    }
}
over 4 years ago · Santiago Trujillo Report

0

This is not the right approach for doing it. Every time you call the service , it initialize a new instance and hence you get a false.

You should create a singleton service instance ( via the main module in your app) - where it will contain your app state ( in memory / localstorage)

Then , when you'll call UserAuthenticationService - you won't update its owbn parameter but the main's one ( the singleton).

I suggest you to use a BehaviourSubject ( read about it , it's like a Subject but it also yields its last value without waiting to emit a value manually).

From that point your app can see from anywhere ig the user is logged in or not.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!