![](/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.