Angular 2 - Displaying async Object data from promise

前端 未结 7 900
野性不改
野性不改 2020-12-02 22:57

Edit: It looks like my main problem now is that I can\'t seem to display async data from an object. I have a promise containing the data object, and when I use



        
7条回答
  •  青春惊慌失措
    2020-12-02 23:30

    The OP asked for promises but in case people are using Observables, adapting @user2884505's answer, since pluck isn't directly available on observables as a method in recent versions of RxJS, you may have something like this :

    import { Pipe, PipeTransform } from '@angular/core';
    
    import { Observable } from 'rxjs';
    import { pluck } from 'rxjs/operators';
    
    @Pipe({
      name: 'asyncKey',
      pure: false
    })
    export class AsyncKeyPipe implements PipeTransform {
      private observable: Observable;
      private result: Object;
    
      transform(value: any, ...args: any[]): any {
    
        if (!this.observable) {
          this.observable = value.pipe(pluck(...args));
          this.observable.subscribe(r => this.result = r);
        }
    
        return this.result;
      }
    }
    
    
    

    And then, you can use it, even for nested keys :

    {{ user$ | asyncKey: 'address' : 'street' }}
    

    提交回复
    热议问题