作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我有一个向 api 发出请求的服务,根据它的响应,我应该决定是否必须加载一个组件。但是由于接收响应需要花费时间,无论响应状态如何,组件都会加载,并且在收到响应一段时间(大约 0.5 秒)后,如果不能加载组件,我们将导航到其他地方。我不希望在收到响应之前加载组件。
我在 Angular 4 中使用 AuthGuard 中的 canActivate 函数,如下所示:
export class AuthGuard implements CanActivate {
access = true;
res: any;
constructor(private router: Router, private routeService: RouteService){}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
setTimeout(() => {
if( !this.exept.includes(this.router.url) ){
this.routeService.FormOperation(this.router.url).subscribe(item=> {
this.res = item;
if (this.res.status == 200) {
if (this.res.data.Access[1] == false) {
this.access = false;
}
if (this.access == true)
{
return true;
}
else {
this.router.navigate(['/dashboard']);
return false;
}
})
}
},0);
if (sessionStorage.getItem('token') && this.access)
{
// logged in so return true
return true;
}
// not logged in so redirect to login page with the return url
this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }});
return false;
}
我正在使用 setTimeout 以便我可以获得正确的 this.router.url 。
更新:
我添加了解析器如下:
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): void {
this.routeService.FormOperation(this.router.url).toPromise()
.then(response => {
this.form_operation_data = response;
if(!this.form_operation_data['data']['Access'][1]) {
this.router.navigate(['/dashboard']);
}
})
.catch(err => {
console.error(err);
});
}
但组件仍会在响应数据收到之前加载 ...
最佳答案
你是如此接近:你的 AuthGuard 应该返回 true
或 false
,并且根据这个值,路由将被激活或不激活。现在你必须将这个 auth guard 添加到你的路由中(这里是激活子路由的示例)。如果您想在组件加载之前获取数据,您可以使用解析器。
解析器
/* Imports */
@Injectable()
export class DataResolverService {
constructor(
private _serviceToShareData: ServiceToShareData,
private _serviceToGetData: ServiceToGetData,
) { }
/* An example with Promise */
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<void> {
return this._serviceToGetData.anyRequestToApi()
.then(response => this._serviceToShareData.setData(response))
.catch(err => {
console.error(err);
});
}
}
现在您可以从您的组件中的 ServiceToShareData 服务获取数据,您希望用这些数据加载它。
路由模块
/* Other imports */
import {DataResolverService } from './path-to-service/data-resolver-service'
import {AuthGuard} from './path-to-service/auth-guard'
const routes: Routes = [
{
path: 'app',
component: ParentComponent,
children: [
{
path: 'child-route',
component: childRouteComponent,
canActivate: [AuthGuard],
resolve: {
data: DataResolverService
}
}
]
}
];
/* Other stuff like @NgModule and class export*/
关于javascript - 如何在加载组件 Angular 4 之前获得服务响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47367738/
我是一名优秀的程序员,十分优秀!