如何在angular2中使用Observable?

时间:2017-07-14 13:50:34

标签: angular typescript angular2-routing angular2-services

我在我的应用程序中使用Guards。如果我刷新,页面不会再次加载跳转#。

问题是警卫。在刷新时,它没有loginUser。

在我的情况下,我不知道如何使用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);
    }

我的服务:

@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;
}

}

我怎么能在这里做异步电话?

1 个答案:

答案 0 :(得分:3)

将防护变为异步:

@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);
    }

然后将您的服务更改为异步:

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;
}

我删除了setLoggedInUsergetLoggedInUser功能,因为它们并不是真正需要的,如果你这样做,你应该直接在该属性上使用getset那里需要额外的代码。