Using an array from Observable Object with ngFor and Async Pipe Angular 2

后端 未结 4 528
南笙
南笙 2020-12-08 03:25

I am trying to understand how to use Observables in Angular 2. I have this service:

import {Injectable, EventEmitter, ViewChild} from \'@angular/core\';
i         


        
相关标签:
4条回答
  • 2020-12-08 03:59

    Who ever also stumbles over this post.

    I belive is the correct way:

      <div *ngFor="let appointment of (_nextFourAppointments | async).availabilities;"> 
        <div>{{ appointment }}</div>
      </div>
    
    0 讨论(0)
  • 2020-12-08 04:04

    Here's an example

    // in the service
    getVehicles(){
        return Observable.interval(2200).map(i=> [{name: 'car 1'},{name: 'car 2'}])
    }
    
    // in the controller
    vehicles: Observable<Array<any>>
    ngOnInit() {
        this.vehicles = this._vehicleService.getVehicles();
    }
    
    // in template
    <div *ngFor='let vehicle of vehicles | async'>
        {{vehicle.name}}
    </div>
    
    0 讨论(0)
  • 2020-12-08 04:04

    If you don't have an array but you are trying to use your observable like an array even though it's a stream of objects, this won't work natively. I show how to fix this below assuming you only care about adding objects to the observable, not deleting them.

    If you are trying to use an observable whose source is of type BehaviorSubject, change it to ReplaySubject then in your component subscribe to it like this:

    Component

    this.messages$ = this.chatService.messages$.pipe(scan((acc, val) => [...acc, val], []));
    

    Html

    <div class="message-list" *ngFor="let item of messages$ | async">
    
    0 讨论(0)
  • 2020-12-08 04:26

    I think what u r looking for is this

    <article *ngFor="let news of (news$ | async)?.articles">
    <h4 class="head">{{news.title}}</h4>
    <div class="desc"> {{news.description}}</div>
    <footer>
        {{news.author}}
    </footer>
    

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