2017-03-01 61 views
1

我不明白爲什麼相同的代碼不能從app.component工作,這在auth.guard中是完美的。爲什麼不在app.component中工作,而是在auth.guard中工作?

我已經寫一些代碼來檢查該用戶登錄到服務器或不併用canActivate在路由定義auth.guard像下面

路由

{ path: 'dashboard', component: DashboardComponent , canActivate: [AuthGuard] } 

AuthGuard

import { Injectable } from '@angular/core'; 
import { Router, CanActivate } from '@angular/router'; 
import { AuthService} from './services/auth.service'; 
@Injectable() 
export class AuthGuard implements CanActivate { 
     constructor(private authService:AuthService, private router:Router) { } 
      canActivate(next:ActivatedRouteSnapshot, state:RouterStateSnapshot) { 
       return this.authService.isAuth().map(e => { 
        if (e) { 
         return true; 
        } 
       }).catch(() => { 
        this.router.navigate(['/login']); 
        return Observable.of(false); 
       }); 
      } 
    } 

它工作正常,但無法在AppComponent中工作 AppComponent

import { Component } from '@angular/core'; 
import { OnInit } from '@angular/core'; 
import { Router } from '@angular/router'; 
import { AuthService } from './services/auth.service'; 
@Component({ 
    moduleId: module.id, 
    selector: 'my-app', 
    templateUrl: './views/app.component.html', 
    styleUrls: [ './styles/app.component.css' ] 
}) 
export class AppComponent implements OnInit{ 
    title = 'Jiffy'; 
    status:boolean; 
    swap:boolean=true; 
    constructor(authService:AuthService, private router:Router){ 
    return this.authService.isAuth().map(e => { 
     if (e) { 
      return true; 
     } 
    }).catch(() => { 
     this.router.navigate(['/login']); 
     return Observable.of(false); 
    }); 
    } 
} 

我不理解爲什麼它是在這裏工作?

錯誤

Error: Uncaught (in promise): TypeError: Cannot read property 'isAuth' of undefined TypeError: Cannot read property 'isAuth' of undefined at new AppComponent

AuthService

isAuth(){ 
     return this.http.get("/account/check") 
     .map(function(res){ 
      return status=res.json().status; 
     }); 
    } 

Express服務器與護照

router.get('/check', function(req, res,next) { 
    if (req.isAuthenticated()){ 
    return res.send({"status":true}); 
    } 
    return res.send({"status":false}); 
}); 
+0

有沒有更多的細節可以給我們?記錄任何錯誤?每種情況下'isAuth'的結果是什麼? – Adam

+0

已編輯關於服務和服務器方法。我正在使用Passport它正在返回true或false –

回答

2

如果您想在組件中使用this,則需要將publicprivate添加到構造函數中的參數中。

constructor(private authService:AuthService, private router:Router) 
+1

它工作。謝謝 –

0

錯誤是說個在authService是未定義的。你有沒有在你的app.module中聲明AuthService作爲提供者?

+0

是的男人!那是爲什麼工作是AuthGuard,不是嗎? –

+0

我認爲你需要在構造函數中添加'private'關鍵字,否則Angular將不知道注入該服務。 –

相關問題