Aji*_*man 3 javascript typescript angular
我正在创建一个管道来将一种货币价值转换为另一种货币价值。我正在进行 HTTP 调用以转换值。
@Pipe({
name: "currencyConverter"
})
export class CurrencyConverterPipe implements PipeTransform {
transform(value: number, currencyPair: string): number {
let sourceCurrency = currencyPair.split(":")[0];
let destinationCurrency = currencyPair.split(":")[1];
this.currencyConverterService.convert(sourceCurrency, destinationCurrency).subscribe(successData => {
return successData['fiatValue'] * value;
}, errorData => {
console.error(errorData);
})
}
}
Run Code Online (Sandbox Code Playgroud)
在 HTML 中
<p> {{ value | currencyConverter:'BTC:USD'}}</p>
Run Code Online (Sandbox Code Playgroud)
我无法在 UI 中看到任何值。当我制作管道时impure,它可以工作,但它正在向服务器发出许多 HTTP 调用。有没有办法在不使用pure: false管道的情况下进行 HTTP 调用
这个管子在设计上不是纯的。
为了不引起多个请求,它应该返回相同的 observable,在输入更改之前不会执行其他请求,例如:
@Pipe({
name: "currencyConverter",
pure: false
})
export class CurrencyConverterPipe {
private sourceCurrency;
private destinationCurrency;
private valueSubject = new Subject();
private value$ = this.valueSubject.asObservable().distinctUntilChanged()
.switchMap(value => {
return this.currencyConverter
.convert(sourceCurrency, destinationCurrency))
.map((data) => data * value);
});
constructor(private currencyConverter: ...) {}
transform(value: number, currencyPair: string): number {
this.sourceCurrency = currencyPair.split(":")[0];
this.destinationCurrency = currencyPair.split(":")[1];
this.valueSubject.next(value);
return this.value$;
}
}
Run Code Online (Sandbox Code Playgroud)
由于它应该仅与async管道结合使用,因此将它们连接在一起并扩展是有意义的AsyncPipe:
@Pipe({
name: "currencyConverterAsync",
pure: false
})
export class CurrencyConverterPipe extends AsyncPipe {
private sourceCurrency;
private destinationCurrency;
private valueSubject = new Subject();
private value$ = this.valueSubject.asObservable().distinctUntilChanged()
.switchMap(value => {
return this.currencyConverter
.convert(sourceCurrency, destinationCurrency))
.map((data) => data * value);
});
constructor(cdRef: ChangeDetectorRef, private currencyConverter: ...) {
super(cdRef);
}
transform(value: number, currencyPair: string): number {
this.sourceCurrency = currencyPair.split(":")[0];
this.destinationCurrency = currencyPair.split(":")[1];
this.valueSubject.next(value);
return super.transform(this.value$);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2386 次 |
| 最近记录: |