2017-07-14 17 views
1

私のアプリケーションでガードを使用しています。私がリフレッシュすると、ページは#にジャンプして再びロードされません。observable in angular2の使い方は?

問題はGuardです。リフレッシュ時にloginUserはありません。私の場合は

私は、観察を使用する方法がわからない:

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

その後、同様asyncを指定するために、あなたのサービスを変更します:

答えて

3

変更ガードが非同期であることを彼らが本当に必要としないよう

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を直接プロパティで使用する必要があります。

+0

@AluanHaddadあなたは 'isUserinGroup'メソッドの意味ですか? 'then'コールバックから' true'または 'false'を返すことで、' async'なしで同等に書くことができます。 'Promise.resolve'は必要ありません。私はあなたが 'async'から得た平坦化がコードをよりきれいにすると思うので、私はいずれにしても同意しないと思う。 – Duncan

+0

申し訳ありませんが、私は 'await'を逃しました。 –

+0

あなたの答えは@Duncan thxですが、これは機能しません。 laodeでアプリケーションはフリーズモードになっています。私は何もできません。どこでも私はisUserinGroupメソッドを呼び出す非同期を追加します。 – trap

関連する問題