我正在使用路由守卫,特别是 canActivate()
方法,但是 Angular 正在调用我的根 AppComponent
的 ngOnInit()
< em>在 canActivate
被调用之前。
在 AppComponent
可以在模板中呈现它之前,我必须等待 canActivate
中的一些数据。
我该怎么做?
最佳答案
我正在处理这种情况,这是我通常做的:
1. 我创建了一个Resolver 服务(它实现了Resolve
接口(interface))。它允许您在激活路线之前获取所有必要的数据:
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
接口(interface):
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. 然后你可以将 Resolver 和 AuthGuard 添加到你的路由配置中,这里只是一部分(路由的结构可以不同,这里是一个激活父组件的例子):
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 调用并将对类属性的响应的必要部分存储在 DataService
通过 setResult
方法(这是通常的 setter)。然后,当解析器完成工作时,就到了我们的 AuthGuard
的时候了。它通过 getResult
方法(它是通常的 getter)从 DataService
获取存储的结果,并返回这个 bool 结果(我们的 AuthGuard
期望返回 bool 值, 返回true
则激活路由,返回false
则不激活);
这是最简单的例子,没有对数据进行任何额外的操作,逻辑通常更复杂,但这个框架应该足以基本理解。
关于javascript - 为什么在 canActivate() 之前调用 ngOnInit()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50747839/