我将用管道解析ID。
我认为这不是每次调用service / 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>
答案 0 :(得分:1)
首先,您需要返回Observable
。当您致电subscribe()
时,将返回Subscription
。此外,您需要实际从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
管道订阅Observable
返回的transform
并使用结果值进行绑定。