简体   繁体   中英

Angular2: Rendering data from Observables

Following interpolation

{{ (__responseData | async)?.calculation | json }}

outputs following structure

[
    {
        "gross": 26.625834,
        "net": 20.425833,
        "tax": 6.2000003
    }
]

How can I get gross?

{{ (__responseData | async)?.calculation[0].gross }}

does not work, and the all the following trys don't work too:

{{ (__responseData.calculation[0] | async)?.gross }}
{{ (__responseData.calculation.[0].gross  | async) }}

What's the mistake?

EDIT: As workaround I use flatmap ( this.__responseData.flatMap((data: any) => data.calculation); ) but I would like to have an elegant solution,..

That's the answer from Alexander (Angular2-Github-Platform)

You could use *ngFor="let calculation of calculations | async"

@Component({
  selector: 'my-app',
  providers: [HTTP_PROVIDERS],
  template: `
    <div *ngFor="let calculation of calculations | async">
      Gross: {{ calculation.gross }}<br>
      Net: {{ calculation.net }}
    </div>
  `,
  directives: [NgFor]
})
export class App {
  calculations: Observable<{gross:number; net:number}[]>;

  constructor(private _http: Http) {
    this.calculations = this._http.get("./data.json")
                            .map(res => res.json().calculation)
  }
}

http://plnkr.co/edit/3ze70dYycQxNyXA286mX?p=preview

Is it not a bug. It is because you are doing elvis operator ( ?. ) on the calculation . In case the service is not done yet, you'll get null out of that first part (__responseData | async)?.calculation , then you immediately get the first element out of a null value, and that's when the error happens.

To avoid exception in this case, you have to make sure (__responseData | async)?.calculation is not null before trying to go further down. As far as I know, we do not have ?[i] operator for array, so I suggest you go with a helper method.

I've done that in this plunker for your reference: http://plnkr.co/edit/pkZW9lQfk1f5hKczKtim?p=preview

Or this: http://plnkr.co/edit/ybvEvAr4t7dUvmAfFf3q?p=preview

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM