6

我正在使用路由保护,特别是canActivate()方法,但是 Angular 在调用之前ngOnInit()调用了我的根。AppComponent canActivate

我必须等待一些数据canActivate才能AppComponent在模板中呈现它。

我怎样才能做到这一点?

4

2 回答 2

3

我正在处理这种情况,这是我通常做的事情:

1.我创建了一个解析器服务(它实现了Resolve接口)。它允许您在激活路线之前获取所有必要的数据:

import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, Resolve, RouterStateSnapshot } from '@angular/router';
import { DataService } from 'path/to/data.service';

@Injectable()
export class ExampleResolverService implements Resolve<any> {
  constructor(private _dataService: DataService) { }

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<any> {
    return this._dataService.anyAsyncCall()
      .then(response => {
        /* Let's imagine, that this method returns response with field "result", which can be equal to "true" or "false" */
        /* "setResult" just stores passed argument to "DataService" class property */
        this._dataService.setResult(response.result);
      })
      .catch(err => this._dataService.setResult(false););
  }
}

2.下面是我们如何处理AuthGuard,它实现了CanActivate接口:

import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot } from '@angular/router';
import { DataService } from 'path/to/data.service';

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private _dataService: DataService) { }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    /* "getResult" method operates with the same class property as setResult, it just returns the value of it */
    return this._dataService.getResult(); // will return "true" or "false"
  }
}

3.然后你可以在你的路由配置中包含ResolverAuthGuard,这里只是一部分(路由的结构可以不同,这里是一个激活父组件的例子):

const routes: Routes = [
  {
    path: 'app',
    component: AppComponent,
    resolve: {
      result: ExampleResolverService // your resolver
    },
    canActivate: [AuthGuard], // your AuthGuard with "canActivate" method
    children: [...] // child routes goes inside the array
  }
];

这个怎么运作

当您导航到/app时,ExampleResolverService开始,进行 API 调用并将响应的必要部分存储在DataServiceviasetResult方法中(它是通常的设置器)中的类属性。然后,当解析器完成工作时,我们的AuthGuard. DataService它从viagetResult方法(它是通常的 getter)中获取存储的结果,并返回这个布尔结果(我们AuthGuard期望返回布尔值,如果它返回将激活路由,如果返回true则不会激活false);

这是最简单的例子,没有对数据进行任何额外的操作,逻辑通常更复杂,但这个骨架应该足以基本理解。

于 2018-06-07T19:54:46.067 回答
0

对我来说,我在我的应用组件中监听了 ROUTE_NAVIGATED 事件,如下所示

我正在使用ngrx/router-store来监听这些路由器操作。

  // app.component.ts
  public ngOnInit(): void {
    // grab the action stream
    this.actions$.pipe(
      // Only pay attention to completed router 
      ofType(ROUTER_NAVIGATED),
      // Now I can guarantee that my resolve has completed, as the router has finsihed
      // Switch 
      switchMap(() => {
        // Now switch to get the stuff I was waiting for 
        return this.someService.getStuff();
      })
    // Need to subscribe to actions as we are in the component, not in an effect
    // I suppose we should unsubscribe, but the app component will never destroy as far as I am aware so will always be listening
    ).subscribe();
于 2020-04-10T19:46:24.543 回答