简体   繁体   中英

How to make Angular component UI wait for Asynchronous function

What I am doing is I am subscribing a http get function that validates my user in my singup component. Now what I want is I want to make it wait until I get the data and navigate away to my internal page. I am trying to navigate to internal page after validation is successful. But it works just after UI is ready. I mean I still see signup page after refreshing for 1 second. The code is given below

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

I tried to put this code in constructor() and ngInit() but same thing is happening.

As mentioned by @yurzui in the comments section, angular guards prevent views from rendering if the guard validation fails (component life cycle will not be triggered if guard fails).

Checkout this sample code snippet that you can use to add a guard for authenticated views in your application -

Guard Definition

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();
        });
    }
}

Route Definition

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,
    }];

Do checkout this SO answer to know how to trigger multiple guards in series as it most of the times creates problems because angular doesn't fire guards in series.

I hope this helps you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM