使用服务解析管道中的 id

Resolve id in pipe with a service

我会用管道解析一个ID。

我认为这不是每次都调用 service/api 的最佳方式吗?

以前把所有国家存起来是不是比较好?我怎么能return管道中的国家名称?

服务:

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

管道:

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)
    )
  }
}

编辑:

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

首先你需要return一个Observable。当您调用 subscribe() 时,将 return 调用 Subscription。此外,您实际上需要 return 来自 transform() 的内容,因此添加了 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
      });
    )
  }
}

那么你可以像

一样使用管道
<div>{{someId | myIdPipe | async}}</div>

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

async 管道订阅来自 transformObservable return 并将结果值用于绑定。