orangeeez
orangeeez

Reputation: 9

*ngFor output filtering by pipes

I have a HTML construction like:

<div *ngFor="#notification of notifications"
      [innerHTML]="notification | notificationHTML">
</div>

And a notificationHTML pipe:

transform(notification: string, args: any[]): any {
var example: any;
this._service.GetExample(notification)
     .subscribe(e => {
         example = e;
      });
return "<span>" + example + "</span>";
}

The problem is that example variable is equal to undefined, because function GetExample does not have time to execute on time. How can I solve this?

Upvotes: 0

Views: 249

Answers (2)

Madhu Ranjan
Madhu Ranjan

Reputation: 17914

You may try below,

Return an Observable from your Pipe transform and then use async pipe

Component template

 <div *ngFor="#notification of notifications"
   [innerHTML]="notification | notificationHTML | async">
 </div>

Pipe

  notificationObservable: Subject<any> = new Subject<any>();

  transform(notification: string, args: any[]): any {
   this._service.GetExample(notification)
      .subscribe(e => {
         this.notificationObservable.next("<span>" + e+ "</span>");
     });
   return notificationObservable;
  }

Here is the Plunker!!

Hope this helps!!

Upvotes: 1

quadthagoras
quadthagoras

Reputation: 45

I assume GetExample returns an observable of some sort. If so, there's no guarantee that your subscription will be triggered before transform returns. Either you'll have to make the GetExample method synchronous, or you'll have to cache the value returned by the subscription and use it whenever transform gets called.

Upvotes: 0

Related Questions