trap
trap

Reputation: 2640

How to use Observable in angular2?

I am using Guards in my application. If I do a refresh, the page does not load again an jumps on #.

The problem is the Guard. On refresh it does not have the loginUser.

In my case I do not know how to use the observable:

@Injectable()
export class MyComponentGuard implements CanActivate {
    constructor(private _userService: UserService) { }
    //on refresh it returns false because the loginUser is null
    canActivate() {
        return this._userService.isUserinGroup(UserGroup.CALL_CENTER);
    }

my service:

@Injectable()
export class UserService {

private loggedInUser: User = null;

constructor(private _httpService: HTTPService) { }

//this is called in root component
public loadUser() {
        this._httpService.getAuthenticationUser()
            .subscribe(this.setLoggedInUser.bind(this));
    }

private setLoggedInUser(user: User) {
    this.loggedInUser = user;
}

public getLoggedInUser(): User {
    return this.loggedInUser;
}

public isUserLoggedIn(): boolean {
    return this.loggedInUser != null;
}

public isUserinGroup(group: UserGroup): boolean {
    //here is the problem the user is on refresh null
   if (!this.loggedInUser) {
        return false;
    }

    for (var userGroup of this.loggedInUser.authGroups) {
      //  if in group return true
    }
    return false;
}

}

how can I do here a async call?

Upvotes: 1

Views: 79

Answers (1)

Duncan
Duncan

Reputation: 95632

Change the guard to be async:

@Injectable()
export class MyComponentGuard implements CanActivate {
    constructor(private _userService: UserService) { }
    //on refresh it returns false because the loginUser is null
    async canActivate(): Promise<boolean> {
        return this._userService.isUserinGroup(UserGroup.CALL_CENTER);
    }

Then change your service to be async as well:

public loggedInUserPromise: Promise<User> = null;

constructor(private _httpService: HTTPService) { }

//this is called in root component
public loadUser() {
    if (!this.loggedInUserPromise) {
        this.loggedInUserPromise = this._httpService.getAuthenticationUser().toPromise();
    }
}

public async isUserinGroup(group: UserGroup): Promise<boolean> {
   if (!this.loggedInUserPromise) { this.loadUser(); }

   const user: User = await this.loggedInUserPromise;
   if (!user) {
        return false;
    }

    for (var userGroup of user.authGroups) {
      //  if in group return true
    }
    return false;
}

I removed the setLoggedInUser and getLoggedInUser functions as they aren't really needed and you should be using get and set directly on the property if you do come to need additional code there.

Upvotes: 3

Related Questions