有一种方法可以在管道中注入和调用服务吗?我有货币服务,我想用它来获取基于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搜索不纯的缓存管,
Let’s write one more impure pipe,a pipe that makes an HTTP request to
the server. normally,that’s a horrible idea. It’s probably a horrible
idea no matter what we do. We’re forging ahead anyway to make a point.
Remember that impure pipes are called every few microseconds. If we’re
not careful,this pipe will punish the server with requests.
牢记这一点,您可以在下面针对您的场景进行异步获取结果,
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 !!
希望这可以帮助!!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。