![](/img/trans.png)
[英]“No provider for AuthGuard!” using CanActivate in Angular 2
[英]Angular AuthGuard canActivate
AuthGuard 會阻止它應該阻止的一切。 但是當我返回 true 時,會發生一件不受歡迎的事情。 我在控制台中得到一個“測試”,但不是讓我進入 /test,而是將我重定向到 /。 為什么? 它是 app.module.ts 中的 RouterModule:
RouterModule.forRoot([
{ path: 'test', component: HomeComponent, canActivate: [AuthGuard] },
{ path: 'account/register', component: RegisterComponent }
], { relativeLinkResolution: 'legacy' })
它是 AuthGuard:
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router } from '@angular/router';
import { CookieService } from 'ngx-cookie-service';
import { Observable } from 'rxjs';
import { AuthService } from '../services/auth.service';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private _authService: AuthService, private _cookieService: CookieService, private router: Router) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
const tokenExists: boolean = this._cookieService.check("token");
if (tokenExists == true) {
const token = this._cookieService.get("token");
this._authService.isAuthenticated(token).subscribe(data => {
if (data as any == true) {
console.log("test");
return true;
}
else if (data as any == false) {
this.router.navigate(['account/register']);
return false;
}
else {
this.router.navigate(['account/register']);
return false;
}
});
}
else {
this.router.navigate(['account/register']);
return false;
}
}
}
為什么會這樣?
您也應該返回訂閱 scope。 重構為
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree { const tokenExists: boolean = this._cookieService.check("token"); if (tokenExists == true) { const token = this._cookieService.get("token"); return this._authService.isAuthenticated(token).subscribe(data => { if (data as any == true) { console.log("test"); return true; } else if (data as any == false) { this.router.navigate(['account/register']); return false; } else { this.router.navigate(['account/register']); return false; } }); } else { this.router.navigate(['account/register']); return false; } }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.