1

我将用管道解析一个 ID。

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

之前存储所有国家会更好吗?我怎样才能在管道中返回国家名称?

服务:

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>
4

1 回答 1

1

首先,您需要返回一个Observable. 当您调用subscribe()aSubscription时,将返回。此外,您还需要实际返回一些东西,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管道订阅返回的Observablefromtransform并将结果值用于绑定。

于 2016-12-22T08:26:08.800 回答