How to make Angular2 wait for a promise in front of a rendering component

Firstly: Yes, I have Googled it in advance, and the solution that appeared does not work for me.

Context

I have an Angular 2 component that calls a service, and it needs to do some data manipulation after receiving a response:

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

In its template, this data is passed to the child component:

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

This causes an error that the child receives myData as undefined. The Google result published above talks about using Resolver , but this does not work 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 the same when I add MyDataResolver to the providers property in app.component.ts :

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

Is the interface changed to use this parameter?

+6
source share
1 answer

The router maintains the promise or observable returned with resolve() .
See also https://angular.io/docs/ts/latest/api/router/index/Resolve-interface.html

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

+3
source

All Articles