我目前正在开发一个Angular网页,在后端使用python API。我想添加一个canActivate Guard,以确保用户位于管理员列表中,并放置在另一个服务器上。
我的问题是,似乎守卫不等待API的响应,我在守卫本身用window.alert测试它,它向我展示了一个“未定义”的输出。当我在我的auth.service中测试我的方法时,我在console.log中得到了正确的响应,所以我的方法似乎返回了正确的布尔值,但我的警卫似乎不等待API的答案。
我得到以下代码:
auth.service.ts:
import { HttpClient} from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { IAuth } from './IAuth';
@Injectable({
providedIn: 'root'
})
export class AuthService {
constructor(private http: HttpClient) { }
Acc: boolean;
getauth(): Observable<IAuth['Access']> {
return this.http.get<IAuth['Access']>('http://x.x.x.x:5555/auth');
}
get Access(): boolean {
this.getauth().subscribe( data =>
this.Acc = data);
return this.Acc;
}
}
这是我的auth.guard.ts:
import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthService} from './auth.service';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor (
private auth: AuthService,
private router: Router
) {}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
if (!this.auth.Access) {
this.router.navigate(['/noaccess']);
window.alert(this.auth.Access);
window.alert(this.auth.Acc);
}
return true;
}
}
我希望你们可以帮助我解决这个问题,就像我说的那样,我在后卫(未定义)中获得错误的响应,访问属性并访问方法。
get Access(): boolean {
this.getauth().subscribe( data => this.Acc = data);
return this.Acc;
}
你不等待你的HTTP调用完成,所以你的警卫也不会。请改用它。
get Access(): Observable<any> {
return this.getauth().pipe(tap(data => this.Acc = data));
}
你守卫然后成为
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
return this.auth.Access.pipe(map(res => {
if (!res) { this.router.navigate(['/noaccess']); }
return !!res;
}));
}