2017-07-14 51 views
1

我在我的應用程序中使用了衛兵。如果我進行刷新,頁面不會再次加載#上的跳轉。如何在angular2中使用Observable?

問題是警衛。刷新時它沒有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; 
} 

}

我怎麼可以在這裏做一個異步調用?

回答

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

+0

@AluanHaddad你是指'isUserinGroup'方法嗎?您可以通過從'then'回調函數中返回true或false來不使用'async'來平等地編寫它,不需要'Promise.resolve'。我認爲無論如何我都不同意,因爲我認爲你從'async'獲得的扁平化使得代碼更加清晰。 – Duncan

+0

對不起,我錯過了'await'我同意它寫得更乾淨。 –

+0

@Duncan thx爲您的答案,但這是行不通的。在應用程序處於凍結模式時。我無能爲力。我在任何地方添加一個異步,我稱之爲isUserinGroup方法。 – trap