用Observable或Promise转换Angular 6中的管道



我试图在angular 6中设置Pipe,使用服务(返回可观察的方法)将文本转换为其他文本

我尝试了以下代码,但我需要返回一个字符串,而不是Promise

管道:

import { Pipe, PipeTransform } from '@angular/core';
import { TimeZoneService, TimeZone } from '../services/Global/timezone.service';
//import { resolve } from 'dns';
import { reject } from 'q';
import { Observable } from 'rxjs';
@Pipe({
name: 'utcToText'
})
export class UtcToTextPipe implements PipeTransform {
private timezoneLst: TimeZone[] = [];
constructor(private _timezoneSvc : TimeZoneService) {}
async transform(timezone: any, args?: any){
this.timezoneLst = await this._timezoneSvc.getTimeZonesLst().toPromise();
return this.timezoneLst.find(x => x.utc.indexOf(timezone) > -1).text;
}
}

html:

<span>{{subscription.time_zone |  utcToText}</span>

有什么方法可以让Promise/Oveserve的异步方法变成一个返回同步的同步函数,比如String?

非常感谢你的帮助。

尝试返回Observable<string>并将async链接到现有管道上。此外,您将无法使用API调用的异步特性返回string

管道:

import { Pipe, PipeTransform } from '@angular/core';
import { TimeZoneService, TimeZone } from '../services/Global/timezone.service';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
@Pipe({ name: 'utcToText'})
export class UtcToTextPipe implements PipeTransform {
constructor(private _timezoneSvc : TimeZoneService) {}
transform(timezone: string, args?: any): Observable<string> {
// this assumes getTimeZonesLst() returns an Observable<TimeZone[]>
return this._timezoneSvc.getTimeZonesLst().pipe(
map((timeZones: TimeZone[]) => {
return timeZones.find(x => x.utc.indexOf(timezone) > -1).text;
})
);
}
}

模板:

<span>{{subscription.time_zone | utcToText | async}</span>

下面是一个异步管道的示例,它源自Angular文档中的指数管道示例。

如果由于某种原因,您真的需要使用promise而不是Observable:

import { Pipe, PipeTransform } from '@angular/core';
import { TimeZoneService, TimeZone } from '../services/Global/timezone.service';
import { Observable } from 'rxjs';
@Pipe({ name: 'utcToText'})
export class UtcToTextPipe implements PipeTransform {
constructor(private _timezoneSvc : TimeZoneService) {}
transform(timezone: string, args?: any): Promise<string> {
// this assumes getTimeZonesLst() returns an Observable<TimeZone[]>
return this._timezoneSvc.getTimeZonesLst()
.toPromise()
.then((timeZones: TimeZone[]) => {
return timeZones.find(x => x.utc.indexOf(timezone) > -1).text;
})
}
}

希望这能有所帮助!

最新更新