我正在做的是我正在订阅一个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 answer知道如何触发多个警卫串联,因为它大多数时候会产生问题,因为角度不会连续发射防护装置。
我希望这可以帮助你。