Search code examples
angularresolver

How to make Angular2 wait for a promise before rendering component


First: Yes, I have Googled this beforehand, and the solution that came up isn't working for me.

The Context

I have an Angular 2 component that calls a service, and needs to perform some data manipulation once it receives the response:

ngOnInit () {
  myService.getData()
    .then((data) => {
      this.myData = /* manipulate data */ ;
    })
    .catch(console.error);
}

In its template, that data is passed to a child component:

<child-component [myData]="myData"></child-component>

This is causing an error that the child is getting myData as undefined. The Google result posted above talks about using Resolver but that isn't working for me.

When I create a new resolver:

import { Injectable } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Rx';
import { MyService } from './my.service';

@Injectable()
export class MyResolver implements Resolve<any> {
    constructor(private myService: MyService) {}

    resolve (route: ActivatedRouteSnapshot): Observable<any> {
        return Observable.from(this.myService.getData());
    }
}

app.routing.ts

const appRoutes: Routes = [
  {
    path: 'my-component',
    component: MyComponent,
    resolve: {
        myData: MyDataResolver
    }
  }
];

export const routing = RouterModule.forRoot(appRoutes);

I get an error that there is no provider for MyDataResolver. This is still the case when I add MyDataResolver to the providers property in app.component.ts:

@Component({
  selector: 'my-app',
  templateUrl: 'app/app.component.html',
  providers: [
        MyService,
        MyResolver
  ]
})

Has the interface for using this changed?


Solution

  • The router supports a promise or an observable returned from resolve().
    See also https://angular.io/api/router/Resolve

    This should do what you want:

    @Injectable()
    export class MyResolver implements Resolve<any> {
        constructor(private myService: MyService) {}
    
        resolve (route: ActivatedRouteSnapshot): Promise<any> {
            return this.myService.getData();
        }
    }
    

    See also https://angular.io/docs/ts/latest/guide/router.html#!#resolve-guard