Hi, 

I have implemented an AuthGard which uses the authentication service I also 
uploaded. 
My problem is, that in ngOnInit() of authentication service I fetch config 
infos from server, where I determine if I need a login. 
This service call seems to come to late due to it is asynchron. In 
isLoginNecessary() this.configInfo is undefined. 

Can you give me advice how to refactor my example to get isLoginNecessary() 
called AFTER data from server is set to this.configInfo. 

Thanks in advance 
Best regards
Markus

-- 
You received this message because you are subscribed to the Google Groups 
"Angular and AngularJS discussion" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
Visit this group at https://groups.google.com/group/angular.
For more options, visit https://groups.google.com/d/optout.
import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { AuthenticationService } from '../services/authentication.service';


@Injectable()
export class AuthGuard implements CanActivate {

    authenticationService: AuthenticationService;

    constructor(private router: Router, authenticationService: AuthenticationService) { 
        this.authenticationService = authenticationService 
    }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {

        console.log ("Login needed:                   " + this.authenticationService.isLoginNecessary())
        console.log ("User is logged in:              " + this.authenticationService.isUserLoggedIn ())
        
        if (! this.authenticationService.isLoginNecessary() || this.authenticationService.isUserLoggedIn()) {
            
            return true;
        }
        else {

        // not logged in so redirect to login page with the return url
        this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }});
        console.log("AuthGuard noticed user login is necessary and user is not logged in, redirect to login page")
        return false;
        }
    }
}
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { UserService} from '../api/api/user.service';
import { UserInfo} from '../api/model/userInfo';
import { ConfigurationService} from '../api/api/configuration.service';
import { ConfigInfo} from '../api/model/configInfo'

import 'rxjs/add/operator/map'

@Injectable()
export class AuthenticationService {

    userservice: UserService;
    configservice: ConfigurationService;
    configInfo: ConfigInfo;
    

    constructor(userservice: UserService, configservice:ConfigurationService) {
        this.userservice = userservice;
        this.configservice = configservice
       
    }

    ngOnInit () {
        console.log ("ngOnInit of AutenticationServiec called - yeah")
        
        this.configservice.getConfiguration().subscribe (
            (x) => {
              this.configInfo = x;
            }, 
            (e) => console.log(e), 
            () => console.log('Get configuration completed (' + this.configInfo + ')')
          )
    }

    login(username: string, password: string): Observable<UserInfo> {

        console.log("Authentication service called with " + username + " and password (" + password.length + ")")

        var authenticatedUser = undefined

        return this.userservice.login(username, password)

    }

    isLoginNecessary () : boolean {
       console.log("isLoginNecessary"); 
       console.log(this.configInfo);
       return this.configInfo.loginNeeded
    }
    
    getLastLoginError () : String {
        return localStorage.getItem('lastLoginError')
    }

    isUserLoggedIn (): boolean {
        return this.getLoggedInUser() != undefined;
    }
    
    getLoggedInUser (): string {
        var currentUser = localStorage.getItem('currentUser')
        console.log("get current user " + currentUser)
        return currentUser
    }

    getLoggedInPassword (): string {
        var currentPassword = localStorage.getItem('currentPwd')
        console.log("get current password " + currentPassword ? currentPassword.length : 'undefined')
        return currentPassword
    }

    logout() {
        // remove user from local storage to log user out
        localStorage.removeItem('currentUser')
        localStorage.removeItem('currentPwd')
        localStorage.removeItem('lastLoginError')
    }
}

Reply via email to