Transform pipe in Angular 6 with Observable or Pro

2020-04-20 12:04发布

问题:

I trying to set Pipe in angular 6 that convert text to other with using service (the method that returns observable)

I tried the following code, but I need to return a string instead of Promise

Pipe:

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>

There is any way to make the asynchronous method of Promise / Ovservabe to a synchronous function that returns synchronous such as String?

Thanks a lot for helpers.

回答1:

Try instead returning an Observable<string> and chaining the async onto your existing pipe. Also you simply will not be able to return string with the async nature of your API calls.

Pipe:

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;
      })
    );
  }
}

Template:

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

Here is a example async pipe in action derived from the exponential pipe example in the Angular documentation.

If you really need to use promises instead of observables for some reason:

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;
      })
  }
}

Hopefully that helps!