2017-04-05 55 views
3

我有一個工作的angular2後衛,其中canActivate()調用isLoggedIn()的服務並返回一個承諾,然後解析並處理相應的路由。否定後衛承諾的結果

但是,我試圖做相反的事,看看用戶何時未登錄,並且它不工作。

我想這麼簡單的東西(添加操作!),希望它會工作:

@Injectable() 
export class AuthGuard implements CanActivate { 
    constructor(private authService: AuthService) {} 

    canActivate() { 
     return !this.authService.isLoggedIn(); 
    } 
} 

然而,這總是返回falsey值和路徑從未激活。

這是我isLoggedIn()功能的相關摘錄:

isLoggedIn(): Promise<Boolean> { 
    var component = this; 
    return new Promise((resolve, reject) => {  
     component.queryForUser((user) => { 
     resolve(user != null); 
     }); 
    } 
    }); 
} 

如果用戶不等於null,那麼他登錄並承諾與真正的解決。否則,錯誤。

雖然我可以簡單地添加一個參數指定我找哪個狀態,甚至創造一個isNotLoggedIn()功能,具有相同的邏輯,但倒,我問,有沒有辦法否定的承諾的決心的價值canActivate()

+0

將承諾視爲承諾。 '.then(...)' –

回答

6

return !this.authService.isLoggedIn()將無法​​正常工作,因爲JS是如何工作的。 this.authService.isLoggedIn()是承諾的對象,是真理。 !this.authService.isLoggedIn()將始終是錯誤的。

相反,承諾的結果應該被映射到否定的結果與

canActivate() { 
    return this.authService.isLoggedIn().then(result => !result); 
} 

或者

async canActivate() { 
    return !(await this.authService.isLoggedIn()); 
} 

括號周圍await ...是可選的,用於可讀性。

+0

我是新來的TypeScript。到目前爲止,我已經在'(a)=>(sth(a))'中使用'=>'運算符作爲'function(a){sth(a)}'的簡寫。在這種情況下,'=>'做什麼?這是同樣的事情,甚至更短? –

+1

嚴格地說,它是'函數(a){return sth(a)}',應該始終記住隱式返回,因爲它可能會破壞事物。是的,它是一個參數的簡寫。這是一個使用或不使用它的味道問題。我個人不會在我自己的樣式指南中使用它,因爲它不一致(這裏討論的不一致在http://stackoverflow.com/a/41086381/3731501)。 – estus

3

所有你需要做的是承諾的解析值的一些進一步操作:

canActivate() { 
    return this.authService.isLoggedIn().then(loggedIn => !loggedIn); 
}