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?

1 Answer 1

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}}
Sign up to request clarification or add additional context in comments.

3 Comments

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.
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 stackoverflow.com/questions/36271899/…
To follow up on the comment by @GünterZöchbauer, use the shareReplay operator to prevent multiple API calls.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.