簡體   English   中英

如何在angular2中使用Observable?

[英]How to use Observable in angular2?

我在我的申請中使用了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;
}

}

我怎么能在這里做異步電話?

將防護變為異步:

@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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM