Ran*_*obi 3 promise observable typescript angular angular6
我试图在 angular 6 中设置管道,使用服务将文本转换为其他(返回可观察的方法)
我尝试了以下代码,但我需要返回一个字符串而不是 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;
}
}
Run Code Online (Sandbox Code Playgroud)
html:
<span>{{subscription.time_zone | utcToText}</span>
Run Code Online (Sandbox Code Playgroud)
有什么办法可以让Promise/Ovservabe的异步方法变成String等返回同步的同步函数?
非常感谢帮助者。
Ale*_*sky 18
尝试改为返回 anObservable<string>并将 链接async到您现有的管道上。此外,您将无法以stringAPI 调用的异步性质返回。
管道:
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;
})
);
}
}
Run Code Online (Sandbox Code Playgroud)
模板:
<span>{{subscription.time_zone | utcToText | async}</span>
Run Code Online (Sandbox Code Playgroud)
这是一个从Angular 文档中的指数管道示例派生而来的示例异步管道。
如果由于某种原因你真的需要使用 promises 而不是 observables:
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;
})
}
}
Run Code Online (Sandbox Code Playgroud)
希望这有帮助!
| 归档时间: |
|
| 查看次数: |
7271 次 |
| 最近记录: |