Transform pipe in Angular 6 with Observable or Promise

后端 未结 1 1093
北海茫月
北海茫月 2021-01-21 13:33

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 s

1条回答
  •  野性不改
    2021-01-21 14:28

    Try instead returning an Observable 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 {
        // this assumes getTimeZonesLst() returns an Observable
        return this._timezoneSvc.getTimeZonesLst().pipe(
          map((timeZones: TimeZone[]) => {
            return timeZones.find(x => x.utc.indexOf(timezone) > -1).text;
          })
        );
      }
    }
    

    Template:

    {{subscription.time_zone | utcToText | async}
    

    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 {
        // this assumes getTimeZonesLst() returns an Observable
        return this._timezoneSvc.getTimeZonesLst()
          .toPromise()
          .then((timeZones: TimeZone[]) => {
            return timeZones.find(x => x.utc.indexOf(timezone) > -1).text;
          })
      }
    }
    

    Hopefully that helps!

    0 讨论(0)
提交回复
热议问题