我有一个身份验证卫士,需要运行api调用以查看他们是否具有访问权限。我不认为有可能从订阅返回数据,但是我还能怎么做?
我需要获取用户ID,然后调用api,然后根据api调用返回true或false。
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthService } from 'src/app/services/auth.service';
@Injectable({
providedIn: 'root'
})
export class TeamcheckGuard implements CanActivate {
success: boolean;
constructor(
private router: Router,
private authService: AuthService
) {}
// Checks to see if they are on a team for the current game they selected.
canActivate(next: ActivatedRouteSnapshot,state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
this.authService.getUserId().then(() => {
let params = {
gameId: next.params.id,
userId: this.authService.userId
};
this.authService.getApi('api/team_check', params).subscribe(
data => {
if (data !== 1) {
console.log('fail');
// They don't have a team, lets redirect
this.router.navigateByUrl('/teamlanding/' + next.params.id);
return false;
}
}
);
});
return true;
}
}
答案 0 :(得分:1)
您需要返回Observable<boolean>
,根据身份验证请求,该解析为true / false。
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
return new Observable<boolean>(obs => {
this.authService.getUserId().then(() => {
let params = {
gameId: next.params.id,
userId: this.authService.userId
};
this.authService.getApi('api/team_check', params).subscribe(
data => {
if (data !== 1) {
console.log('fail');
// They don't have a team, lets redirect
this.router.navigateByUrl('/teamlanding/' + next.params.id);
obs.next(false);
}
else {
obs.next(true);
}
}
);
});
});
}
答案 1 :(得分:0)
为什么不使用async并等待这样返回数据
async canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> {
const something = await this.authService.getApi('api/team_check', params)
if (!something ) {
//do authentication
return false;
}
return true;
}