Angular 2 Pipes executing before ngOnInit

4.9k Views Asked by At

I have a implemented a custom Pipe in Angular 2 RC5 which processes data that I get from the server. The problem I'm having is that the Pipe executes before the ngOnInit which is where I am making the calls to the server.

As a test I passed an-already populated list to the Pipe and everything works as expected. The only issue I'm having is that the Pipe executes when the page is rendered. And so the list in that case is empty.

Is there any way to "delay" the rendering of the page so that when the Pipe executes it has the data retrieved from the server?

This is a sample of my code:

Component

ngOnInit() {
    Observable.forkJoin([
        this.testService.get(),
        this.multilingualService.get(localStorage.getItem('currentPage'))
    ]).subscribe(servicesResult => {
        this.mainList = servicesResult[0];
        this.pageMultilinguals = servicesResult[1];
    },
    error => this.handleError(error));
}

Pipe

@Pipe({name: 'multiLang'})
export class MultilingualPipe implements PipeTransform {
    transform(value: string, pageMultilinguals: Multilingual[], context: number): string {

        for (let i = 0; i < pageMultilinguals.length; i++) {
            if (pageMultilinguals[i].reference === value && pageMultilinguals[i].contexTypeId === context) {
                return pageMultilinguals[i].value;
            }
        }
    }
}

Template

<span>{{ 'Test' | multiLang: pageMultilinguals: 9 }}</span>
1

There are 1 best solutions below

8
On BEST ANSWER

When Angular runs change detection the, then the pipe is executed the first time. After the first change detection run, ngOnInit() is called. Delaying the call to your pipe until ngOnInit() wouldn't help at all, because when you make the server call in ngOnInit() doesn't mean you get the response immediately. The HTTP request is an async call and the response comes eventually but ngOnInit() will be completed a long time already.

I think in your case it should be enough to just make the pipe safe for null values so it doesn't cause exceptions when the passed values are null:

@Pipe({name: 'multiLang'})
export class MultilingualPipe implements PipeTransform {
    transform(value: string, pageMultilinguals: Multilingual[], context: number): string {
        if(!value || !pageMultilinguals || !context) {
          return null;
        }
        for (let i = 0; i < pageMultilinguals.length; i++) {
            if (pageMultilinguals[i].reference === value && pageMultilinguals[i].contexTypeId === context) {
                return pageMultilinguals[i].value;
            }
        }
    }
}