2017-03-01 62 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将不知道注入该服务。 –

相关问题