此身份验证防护不适用于 API 响应。当我运行代码时,它总是返回 true。但我想根据 api 响应运行警卫。是他们实现这一目标的方法吗?
import {Injectable} from '@angular/core';
import {CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router, Route} from '@angular/router';
import {
HttpClient,
HttpHeaders
} from '@angular/common/http';
import {Observable} from 'rxjs';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private router: Router, private http: HttpClient) {
}
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
const sendData = {};
sendData['id'] = sessionStorage.getItem('id');
console.log(JSON.stringify(sendData));
const headers = new HttpHeaders()
.set('Content-Type', 'application/json')
.set('token', sessionStorage.getItem('auth') ? sessionStorage.getItem('auth') : 'test');
this.http.post('http://127.0.0.1:5000/auth',
JSON.stringify(sendData), {
headers
})
.subscribe(
(val: any) => {
},
response => {
this.router.navigate(['/login']);
},
() => {
console.log('The POST observable is now completed.');
});
return true;
}
}