Angular - 无法守卫路线

问题描述 投票:0回答:0

我想允许用户根据 api 的返回值浏览某个 url。

这是路线:

{
path: 'request',
component: RequestLayoutComponent,
children: [
  {
    path: 'create',
    component: JobCreateComponent,
    resolve: { canContinue: STResolver },
    canActivateChild: [LimitGuard],
    runGuardsAndResolvers: 'always' 
  }]
}

这是解析器:

@Injectable({
providedIn: 'root'
})
export class STResolver implements Resolve<any>{
constructor(private router: Router, private data: DataService, private inspectionService: InspectionService, private searchForm: SearchForm) {}

resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
    this.searchForm.userId = this.data.localStorageFind()
    let search = this.searchForm
    search.sort = ESort.DESC
    this.inspectionService.getLimit(search).pipe(
        map((res: any) => {
            if (res.status == false) {
                return false;
            }
            return true;
        })
    );
    return
    }
}

这是守卫:

@Injectable({
    providedIn: 'root'
})

export class LimitGuard implements CanActivate {
canContinue: any

constructor(private router: Router, private route: ActivatedRoute) {
    this.canContinue = this.route.snapshot.data.canContinue;
}

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    this.canContinue = this.route.snapshot.data.canContinue;
    if (this.canContinue == true) {
        return true;
    } else {
        this.router.navigate(['/inspections/request']);
        return false;
    }
  } 
}

每次我尝试浏览 url /request/create 它都会抛出这个错误:

ERROR Error: Uncaught (in promise): Error: invalid
Error: invalid
    at Module.lp (main.js:1:471005)
    at hn.children.resolve.canContinue.n.ɵfac [as factory] (798.js:1:107375)
    at Ph.hydrate (main.js:1:457363)
    at Ph.get (main.js:1:455928)
    at Ph.get (main.js:1:455976)
    at ci (main.js:1:631393)
    at mo (main.js:1:658002)
    at main.js:1:658073
    at ne (main.js:1:214335)
    at O (main.js:1:214272)
    at Pe (polyfills.js:1:140142)
    at Pe (polyfills.js:1:139642)
    at polyfills.js:1:141019
    at k.invokeTask (polyfills.js:1:130653)
    at Object.onInvokeTask (main.js:1:557682)
    at k.invokeTask (polyfills.js:1:130574)
    at k.runTask (polyfills.js:1:125676)
    at pe (polyfills.js:1:1330

早些时候,我尝试在 Guard 中进行 api 调用,但仍然出现相同的错误。我处理 Observable 的 promise 值的方式有什么特别不对的地方吗?或者这是另一个问题?

angular angular-router
© www.soinside.com 2019 - 2024. All rights reserved.