Resolve id in pipe with a service

731 Views Asked by At

I will resolve an ID with a pipe.

I think it isn't the best way to call the service/api every time?

Is it better to store all countries before? How could I return the country name within pipe?

service:

getCountry(id:number) {
   return this._http.get(this.apiUrl + "/country/" + id).map(res => res.json());
}

pipe:

export class ResolvePipe implements PipeTransform {
  constructor(public _formDataService: FormDataService) {}
  transform(value: number, args: any[]): any {
    this._formDataService.getCountry(value).subscribe(
      data => console.log(data[0].name)
    )
  }
}

EDIT:

<tr (click)="showProfile(customer)" *ngFor="let customer of (customers | search:term)">
   <td>...</td><td>{{customer.country_id | resolve | async}}</td>
</tr>
1

There are 1 best solutions below

8
On BEST ANSWER

First you need to return an Observable. When you call subscribe() a Subscription will be returned. Also you need to actually return something from transform() hence the added return

export class ResolvePipe implements PipeTransform {
  constructor(public _formDataService: FormDataService) {}
  transform(value: number, args: any[]): any {
    // added `return` and changed `subscribe` to `map`
    return this._formDataService.getCountry(value).map(
      data => {
        console.log(data[0].name);
        return data; // with `{ }` explicit `return` is required
      });
    )
  }
}

then you can use the pipe like

<div>{{someId | myIdPipe | async}}</div>

or

<some-comp [idProp]="someId | myIdPipe | async></some-comp>

The async pipe subscribes to the Observable returned from transform and uses the resulting value for the binding.