Angular 2 - 在管道中调用服务

Mat*_*lez 8 angular

有一种方法可以在管道中注入和调用服务吗?我有货币服务,我想用它来获取基于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);
            }
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

我就是这样用的

{{3 | currencypipe: 2 | async}}
Run Code Online (Sandbox Code Playgroud)

Mad*_*jan 22

您可以像在任何组件中那样在管道中注入服务,

@Pipe({
    name: 'my-currency-pipe'
})
export class MyCurrencyPipe implements PipeTransform {
    constructor(service: SomeService) {

    }

    transform(value: string): string {
        return value;
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,您也可以在管道中使用参数.在这里阅读更多.

更新

管道文档摘录搜索不纯的缓存管道,

让我们再写一个不纯的管道,一个向服务器发出HTTP请求的管道.通常,这是一个可怕的想法.无论我们做什么,这可能都是一个可怕的想法.无论如何,我们都在向前迈进.请记住,每隔几微秒就会调用一次不纯的管道.如果我们不小心,这个管道会根据请求惩罚服务器.

牢记这一点,您可以在下面针对您的场景进行异步获取结果,

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 { }
Run Code Online (Sandbox Code Playgroud)

这是Plunker !!

希望这可以帮助!!

  • 您可以返回承诺或可观察.您需要使用``{{someVal | 我的货币管道 async}}`或``{{(someVal | my-currency-pipe | async)?. someField}}` (3认同)