3

I have created a custom pipe for my application which takes the user id as an argument and returns the user name. For getting all the users I'm making an api call. Therefore, I want to run the loop after I get the users list from the api. I'm doing something like this:

 transform(userId: number): any {
  this.userInfoService.getUsers().subscribe(
    data => {
       this.allUsers = data;
       for(let user of this.allUser) { 
        if(user.id === userId) {
         return user.userName;
        }
       }
      return null;
    },
    error => {
      console.log('Error');
    })
}

But I'm not seeing any value on the UI when I'm using this pipe. The issue I'm suspecting is the value getting returned asynchronously. Any suggestions how this can be fixed?

Aiguo
  • 3,416
  • 7
  • 27
  • 52

1 Answers1

4

I added a return and changed subscribe to map

 transform(userId: number): any {
  return this.userInfoService.getUsers().map(
    data => {
       this.allUsers = data;
       for(let user of this.allUser) { 
        if(user.id === userId) {
         return user.userName;
        }
       }
      return null;
    },
    error => {
      console.log('Error');
    })
}

then use it with the async pipe

{{userId | myPipe | async}}
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • that works like a charm! But, is there any other solution that doesn't make the api call everytime I'm converting userId to userName? Because if I have a long list of userIds in *ngFor, its making the api call for each userId. – Aiguo Aug 24 '17 at 17:15
  • Not sure what you mean exactly by "every time I'm converting userId to userName". You could use a shared service that caches the results. This might help here https://stackoverflow.com/questions/36271899/what-is-the-correct-way-to-share-the-result-of-an-angular-2-http-network-call-in/36291681#36291681 – Günter Zöchbauer Aug 24 '17 at 17:18