Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return async value from a custom pipe: Angular4

Tags:

angular

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?

like image 726
Aiguo Avatar asked Dec 10 '25 03:12

Aiguo


1 Answers

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}}
like image 95
Günter Zöchbauer Avatar answered Dec 12 '25 10:12

Günter Zöchbauer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!