如何使Angular组件UI等待异步功能

时间:2018-03-04 07:20:50

标签: angular angular5

我正在做的是我正在订阅一个http get函数,该函数在我的singup组件中验证我的用户。现在我想要的是我想让它等到我获取数据并导航到我的内部页面。 验证成功后,我试图导航到内部页面。 但它在UI准备就绪后才起作用。我的意思是我在刷新1秒后仍然看到注册页面。 代码如下:

  this._restapiService.validate()
          .subscribe(data=>{
              if(data.success){
                this._router.navigate(['contacts']);
              }
          });

我试着把这段代码放在constructor()和ngInit()中 但同样的事情正在发生。

1 个答案:

答案 0 :(得分:1)

正如@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以了解如何触发多个系列警卫,因为大多数情况下都会产生问题,因为角度不会连续发射警卫。

我希望这会对你有所帮助。