使用带有ngFor和Async Pipe Angular 2的Observable Object中的数组

时间:2016-06-07 03:07:34

标签: typescript angular rxjs observable

我试图了解如何在Angular 2中使用Observables。我有这项服务:

import {Injectable, EventEmitter, ViewChild} from '@angular/core';
import {Observable} from "rxjs/Observable";
import {Subject} from "rxjs/Subject";
import {BehaviorSubject} from "rxjs/Rx";
import {Availabilities} from './availabilities-interface'

@Injectable()
export class AppointmentChoiceStore {
    public _appointmentChoices: BehaviorSubject<Availabilities> = new BehaviorSubject<Availabilities>({"availabilities": [''], "length": 0})

    constructor() {}

    getAppointments() {
        return this.asObservable(this._appointmentChoices)
    }
    asObservable(subject: Subject<any>) {
        return new Observable(fn => subject.subscribe(fn));
    }
}

此BehaviorSubject按其他服务推送新值:

that._appointmentChoiceStore._appointmentChoices.next(parseObject)

我以组件中的observable形式订阅它,我希望将其显示在:

import {Component, OnInit, AfterViewInit} from '@angular/core'
import {AppointmentChoiceStore} from '../shared/appointment-choice-service'
import {Observable} from 'rxjs/Observable'
import {Subject} from 'rxjs/Subject'
import {BehaviorSubject} from "rxjs/Rx";
import {Availabilities} from '../shared/availabilities-interface'


declare const moment: any

@Component({
    selector: 'my-appointment-choice',
    template: require('./appointmentchoice-template.html'),
    styles: [require('./appointmentchoice-style.css')],
    pipes: [CustomPipe]
})

export class AppointmentChoiceComponent implements OnInit, AfterViewInit {
    private _nextFourAppointments: Observable<string[]>

    constructor(private _appointmentChoiceStore: AppointmentChoiceStore) {
        this._appointmentChoiceStore.getAppointments().subscribe(function(value) {
            this._nextFourAppointments = value
        })
    }
}

尝试在视图中显示如下:

  <li *ngFor="#appointment of _nextFourAppointments.availabilities | async">
         <div class="text-left appointment-flex">{{appointment | date: 'EEE' | uppercase}}

但是,可用性仍然是可观察对象的属性,因此它会出错,即使我认为我在可用性界面中定义它也是如此:

export interface Availabilities {
  "availabilities": string[],
  "length": number
}

如何使用异步管道和* ngFor从可观察对象异步显示数组?我得到的错误信息是:

browser_adapter.js:77 ORIGINAL EXCEPTION: TypeError: Cannot read property 'availabilties' of undefined

5 个答案:

答案 0 :(得分:107)

这是一个例子

// 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>

答案 1 :(得分:6)

谁也迷失了这个职位。

我相信是正确的方法:

  <div *ngFor="let appointment of (_nextFourAppointments | async).availabilities;"> 
    <div>{{ appointment }}</div>
  </div>

答案 2 :(得分:2)

我认为您正在寻找的是

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

答案 3 :(得分:1)

如果您没有数组,但是您尝试将可观察对象像数组一样使用,即使它是对象流,也无法在本地运行。假设您只关心将对象添加到可观察对象,而不是删除它们,那么我将在下面显示如何解决此问题。

如果您尝试使用来源类型为BehaviorSubject的可观察对象,请将其更改为ReplaySubject,然后在组件中按如下所示进行订阅:

组件

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

HTML

<div class="message-list" *ngFor="let item of messages$ | async">

答案 4 :(得分:0)

如何在模板中处理此问题。每次将新对象放入数组时,我的循环就会重复

    // in the service
           getVehicles(){
        obj = { data: [{name: 'car 1'},{name: 'car 2'}] }
            return Observable.interval(2200).map(i=> obj.data.push({name: 'car 1'}));
        }


    // in the controller
    vehicles: Observable<Array<any>>
    ngOnInit() {
        this.vehicles = this._vehicleService.getVehicles().obj.data;
    }


// in template
<div *ngFor='let vehicle of vehicles | async'>
    {{vehicle.name}}
</div>

请提出任何建议