2017-04-18 68 views
0

所以我試圖在我的應用程序的某些路線上實施警衛。所以基本上我想發送一個http請求到我的api(後端用express),如果我的會話存在,用戶可以訪問路由。Auth警衛與http請求不適用於Angular 2

我看到很多人在做它的例子,我嘗試了所有的人,但都沒有工作。我在chrome中檢查了開發工具,並且沒有錯誤,我只是看到請求處於「正在等待」狀態。

那麼我做錯了什麼?如果我不做一個http請求,它完美的工作。

我的auth-guard.service.ts

canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot) { 
    return this.authService.isAuthenticated(); 
} 

這是我auth.service.ts

public isAuthenticated() : Observable<boolean> | boolean { 
    let router: Router = this.router; 
    let obs; 

    try { 
     obs = this.http.get('/api/session') 
      .map(result => result.json()) 
      .map(resultJson => (resultJson && resultJson.success)); 

    } catch (err) { 
     obs = Observable.of(false); 
    } 

    return obs 
     .map(success => { 
      // navigate to login page 
      if (!success) 
       router.navigate(['/login']); 

      return success; 
     }); 
} 

這裏是我的API函數

exports.getSession = function(req, res) { 
    return (req.session.passport)? {success: true}: {success: false}; 
} 
+0

如果有請求掛起,這可能意味着,你有一些後端問題,因爲你的Angular客戶端代碼在請求結束時被執行。 –

+0

你是對的!錯誤來自我的後端,謝謝! – Manu

回答

0

確定這樣的錯誤不是來自我的角碼......我不得不改變我在API返回數據的方式,像這樣:

exports.getSession = function(req, res) { 
    let data = (req.session.passport)? {success: true}: {success: false}; 
    return res.send(data); 
} 
相關問題