skip to Main Content

I am making an angular2 application. My biggest problem is the inability to defer loading of main component’s dependent child component till some promise gets resolved.

I have app.component.ts, with class named AppComponent, which I bootstrap in boot.ts like this:

bootstrap(AppComponent, [ROUTER_PROVIDERS, HTTP_PROVIDERS]);

Now I want to call few very vital http services before navigating to my default route, i.e-‘/’. One http service returns data to me that will be used for doing SEO and setting meta data on various routes.

I know that the constructor of any class is called at first, but I don’t know if the constructor waits for the promises to get resolved.

3

Answers


  1. If you use the Router you can use CanActivate otherwise just wrap the template with an *ngIf="dataArrived"

    See also How to pass parameters rendered from backend to angular2 bootstrap method

    Login or Signup to reply.
  2. You could bootstrap asynchronously after your request(s) complete(s). Here is a sample:

    var app = platform(BROWSER_PROVIDERS)
       .application([BROWSER_APP_PROVIDERS, appProviders]);
    
    var service = app.injector.get(CompaniesService);
    
    service.executeSomething().flatMap((data) => {
      var companiesProvider = new Provider('data', { useValue: data });
      return app.bootstrap(appComponentType, [ companiesProvider ]);
    }).toPromise();
    

    See this question for more details:

    and the corresponding plunkr: https://plnkr.co/edit/ooMNzEw2ptWrumwAX5zP?p=preview.

    Login or Signup to reply.
  3. another solution is using a timer in the constructor:

    setTimeout(() => {
        call your function here
    }, 500); 
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search