从我当前的代码中,当使用canActivate路由到页面时,我能够通过以下方式从服务器获取身份验证数据
auth.guard.ts(版本1)
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { Observable } from 'rxjs/Rx';
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Headers, RequestOptions } from '@angular/http';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private router: Router, private http: Http) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.post('/api/authenticate', options )
.map(res => res.json())
.map((res) => {
if (res.response) {
return true;
} else {
this.router.navigate(['/register']);
return false;
}
});
}
}
我想将canActivate中的代码分离到auth.service.ts,如下所示,但它不等待http请求完成并返回
auth.service.ts
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Headers, RequestOptions } from '@angular/http';
import 'rxjs/add/operator/map';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class AuthService {
constructor(private http: Http) { }
authenticate() :Observable<any>{
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.post('/api/authenticate', { options })
.map(res => res.json())
}
}
auth.guard.ts(第2版)
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { Observable } from 'rxjs/Rx';
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Headers, RequestOptions } from '@angular/http';
import { AuthService } from './auth.service';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router, private http: Http) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
if(this.authService.authenticate()){
return true;
}else{
this.router.navigate(['/register])
return false;
}
}
}
我错过了什么?
答案 0 :(得分:1)
auth.guard.ts(第3版)
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router, private http: Http) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
return this.authService.authenticate().map((res) => {
if (res.response) {
return true;
} else {
this.router.navigate(['/register']);
return false;
}
})
}
}
以上代码将链接您的可观察量。但是你的代码还存在另一个问题 - if(res.response) {return true}
,当有响应时,它可能是'用户存在并登录'或'用户不存在'。因此,对于这两种情况,您都要返回true
。你需要修复。