![](/img/trans.png)
[英]How to make a JS function wait for the component to be loaded in angular
[英]How to make Angular component UI wait for Asynchronous function
我正在做的是,我正在预订一个http get函数,该函数可以在singup组件中验证我的用户。 现在,我想要的是等待直到获取数据并导航到内部页面。 验证成功后,我试图导航到内部页面。 但它仅在UI准备好后才起作用。 我的意思是刷新1秒钟后仍然看到注册页面。 代码如下
this._restapiService.validate()
.subscribe(data=>{
if(data.success){
this._router.navigate(['contacts']);
}
});
我试图将这段代码放在Constructor()和ngInit()中,但是正在发生同样的事情。
如@yurzui在评论部分中所述,如果防护验证失败(如果防护失败,则组件生命周期将不会触发),角度防护会阻止呈现视图。
检出此示例代码片段,可用于在应用程序中为经过验证的视图添加保护措施-
import { Injectable } from "@angular/core";
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from "@angular/router";
@Injectable()
export class LoggedInGuard implements CanActivate {
constructor() { }
public canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<any> {
return new Promise<any>((resolve: Function, reject: Function) => {
//this is where you need to validate the user
//it can be an AJAX call
let response: any;
//assuming the AJAX call is made here
//response = HttpService.getData();
//resolve indicates user is validated by the service and guard allows user to land on the reuqested view.
//reject on the other hand, will stop user from landing on requested view
//this logic can be customised.
response.success ? resolve() : reject();
});
}
}
import { Route } from "@angular/router";
import { HomeComponent } from "./components/home.component";
import { LoginComponent } from "./components/login.component";
export const routes: Route[] = [{
path: "route",
canActivate: [LoggedInGuard],
component: HomeComponent,
},{
path: "*",
component: LoginComponent,
}];
请检查这个SO答案,以了解如何串联触发多个警卫,因为在大多数情况下,角度触发不会串联触发多个警卫。
我希望这可以帮助你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.