我有一个这样的解析器:
export class TaskResolver implements Resolve<Documents> {
constructor(private taskService: TaskService) { }
resolve(route: ActivatedRouteSnapshot): Observable<Documents> {
const taskId = route.params.taskId;
return this.taskService.DocumentsTask(taskId);
}
}
在我的组件中,我拥有:
this.route.data.subscribe((data: { documents: Documents }) => {
if (data.documents) {
this.documents = data.documents;
} else {
this.router.navigate([`/error/404`]);
}
});
我需要在解析器内部移动 this.router.navigate([/error/404
)); ,这样解析器将检查数据是否为空并重定向到错误,并且不是组件。或者也许转向使用如下所示的身份验证防护程序
canActivate(route: ActivatedRouteSnapshot): boolean {
const taskId = route.params.taskId;
if (taskId) {
return true;
}
}
DocumentsTask(taskId)返回“可观察”
答案 0 :(得分:0)
CanActivate卫队可以从Angular 7.1.0版本开始返回Observable<boolean | UrlTree>
。这样,防护程序就可以评估boolean
并在评估结果为false时返回路由重定向。
几天前,我写了answer,详细介绍了实现细节,但是在您的情况下,我将按照以下方式处理它:
首先,创建防护:
import { Injectable } from '@angular/core';
import { CanActivate, Router, UrlTree, ActivatedRouteSnapshot } from '@angular/router';
import { Observable, of } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
// import your TaskService here
@Injectable()
export class RequireDocumentsGuard implements CanActivate {
constructor(private router: Router, private taskService: TaskService) {
}
canActivate(route: ActivatedRouteSnapshot): Observable<boolean | UrlTree> {
return this.taskService.DocumentsTask(route.params.taskId).pipe(
catchError(() => of(false)),
map(documents => !!documents || this.router.parseUrl('error/404'))
);
}
}
然后只需在您的RoutingModule
中将守卫添加到您的路线中即可:
{
path: 'your/desired/route/:taskId',
component: YourComponentHere,
canActivate: [RequireDocumentsGuard ]
}
注意: 您尚未发布路线结构,因此我也要指出,您需要确保“错误/ 404”路线实际上存在,例如:
{
path: 'error/404',
component: Your404ErrorComponent
}
希望有帮助!
答案 1 :(得分:-1)
像这样使用Auth Guard:
ng generate guard auth
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from
'@angular/router';
import { Observable } from 'rxjs/Observable';
import { AuthService } from './auth.service';
import {Router} from '@angular/router';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private auth: AuthService,
private myRoute: Router){
}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
const taskId = next.params.taskId;
if (taskId) {
return true;
}else{
this.myRoute.navigate(["/error/404"]);
return false;
}
}
}