我不明白爲什麼相同的代碼不能從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});
});
有沒有更多的細節可以給我們?記錄任何錯誤?每種情況下'isAuth'的結果是什麼? – Adam
已編輯關於服務和服務器方法。我正在使用Passport它正在返回true或false –