【发布时间】:2019-11-13 20:28:02
【问题描述】:
我有一个身份验证守卫,需要运行一个 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;
}
}
【问题讨论】:
-
我建议您编辑问题并更具体地说明您要达到的目标以及遇到的困难。
标签: angular typescript ionic-framework observable ionic4