[英]How can I call a service within a pipe?
There is a way to inject and call a service within a pipe?有没有办法在管道内注入和调用服务? I have a service with currencies and I want to use it to get the name based on the id.
我有一个货币服务,我想用它来获取基于 id 的名称。 Thanks!!
谢谢!!
This is my code:这是我的代码:
@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);
}
);
}
}
And I use it like this我像这样使用它
{{3 | currencypipe: 2 | async}}
You may inject service in pipes like you do in any component,您可以像在任何组件中一样在管道中注入服务,
@Pipe({
name: 'my-currency-pipe'
})
export class MyCurrencyPipe implements PipeTransform {
constructor(service: SomeService) {
}
transform(value: string): string {
return value;
}
}
However you may also use Parameter in pipes.但是,您也可以在管道中使用 Parameter。 Read more here.
在这里阅读更多。
Update更新
excerpts from Pipe documentation search for An impure caching pipe ,摘自 Pipe 文档搜索An不纯的缓存管道,
Let's write one more impure pipe, a pipe that makes an HTTP request to the server.
让我们再写一个不纯的管道,一个向服务器发出 HTTP 请求的管道。 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.
如果我们不小心,这个管道会用请求惩罚服务器。
Keeping above in mind, you can do below for your scenario to get result asynchronously,请记住,您可以在下面为您的场景执行以下操作以异步获取结果,
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 { }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.