Angular 2 – 在管道中调用服务
有一种方法可以在管道中注入和调用服务吗?我有货币服务,我想用它来获取基于id的名称.
谢谢!! 这是我的代码: @Pipe({name: 'currencypipe',pure: false}) export class CurrencyPipe implements PipeTransform { symbol: string = null; constructor(private currencyService: CurrencyService) { } transform(value: number,currencyId: number): Promise<String> { return this.currencyService.getCurrencie(currencyId).then(response => { return (value + " " + response.symbol); } ); } } 我就是这样用的 {{3 | currencypipe: 2 | async}} 解决方法
您可以像在任何组件中那样在管道中注入服务,
@Pipe({ name: 'my-currency-pipe' }) export class MyCurrencyPipe implements PipeTransform { constructor(service: SomeService) { } transform(value: string): string { return value; } } 但是,您也可以在管道中使用参数. Read more here. 更新 excerpts from Pipe documentation搜索不纯的缓存管,
牢记这一点,您可以在下面针对您的场景进行异步获取结果, import { Component,PipeTransform,Pipe } from '@angular/core'; export class CurrencyService { getCurrencie(currencyId):Promise<string> { return new Promise<any>((resolve,reject) => { setTimeout(() => { if(currencyId === 1 ){ resolve({symbol : '$'}); }else{ resolve({symbol: '£'}); } },1000) }) } } @Pipe({name: 'currencypipe',pure: false}) export class CurrencyPipe implements PipeTransform { symbol: string = null; prevalue: string = null; result: string = ''; constructor(private currencyService: CurrencyService) { } transform(value: number,currencyId: number) { if (value !== this.prevalue) { this.prevalue = value; this.result = ''; this.currencyService.getCurrencie(currencyId).then(response => { this.result = value + " " + response.symbol; } ); } return this.result; } } @Component({ selector: 'my-app',template: `<h1>Currency Pipe</h1> <hr /> {{3 | currencypipe: 1 }} ` }) export class AppComponent { } @NgModule({ imports: [ BrowserModule ],declarations: [ AppComponent,CurrencyPipe ],providers: [ CurrencyService ],bootstrap: [ AppComponent ] }) export class AppModule { } 这是Plunker !! 希望这可以帮助!! (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |