简体   繁体   English

如何在管道内调用服务?

[英]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 { }

Here is Plunker !!这里是普朗克!!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在另一个服务提供商内致电服务提供商-angularjs2 - How can I call a service provider within another one - angularjs2 如何在自定义rxjs运算符中调用角度服务? - How can I call an angular service from within a custom rxjs operator? 我可以从管道调用Angular2管道吗? - Can I call an Angular2 pipe from a pipe? 如何在 angular 中的服务文件中的值更改时使用异步 pipe 触发 api 调用? - How can I trigger api calls with async pipe on a value change in the service file in angular? 我如何等待异步管道完成并在不订阅的情况下调用另一个函数 - How can I wait async pipe to finish and call another function after, without subscribing 如何将服务实例传递给Angular库中的组件? - How Can I Pass An Instance Of A Service To A Component Within A Library In Angular? 如何将异步管道放入我的自定义管道中 - How can I put async pipe into my custom pipe 如何在同一个 pipe 中使用 pipe 两个数据流/可观察对象? - How can I pipe two data streams/observables in the same pipe? 我如何调用服务,然后让服务在没有 NullInjectorError 的情况下调用调用组件 - How can i call a service and then have the service make a call to calling component without NullInjectorError 我如何从Angular 2中的指令调用服务 - How can i call a service from a directive in Angular 2
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM