2016-09-14 96 views
2

有一种方法可以在管道内注入和调用服务?我有一个货币服务,我想用它来获取基于id的名称。 谢谢!Angular 2 - 在管道内调用服务

这是我的代码:

@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}} 

回答

7

就像你在任何部件做你可能注入的服务管道,

@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搜索不纯缓存管

让我们写一个更不纯的管道,使一个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 { } 

这里是Plunker

希望这有助于!

+0

谢谢!我这样做了,但是如何使用该服务返回混合数据的值。我尝试设置纯粹的:假设为异步管道并回应承诺,但挂起浏览器。 –

+0

请添加代码你正在尝试。 –

+2

你可以返回一个承诺或观察。您需要使用'{{someVal | my-currency-pipe | async}}或''{{(someVal | my-currency-pipe | async)?. someField}}' –