Использование массива из наблюдаемого объекта с ngFor и Async Pipe Angular 2
Я пытаюсь понять, как использовать Observables в Angular 2. У меня есть эта служба:
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)
Я подписываюсь на него в виде наблюдаемого в компоненте, который я хочу отобразить в нем:
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
}
Как я могу отобразить массив асинхронно от наблюдаемого объекта с помощью async-канала и * ngFor? Сообщение об ошибке, которое я получаю:
browser_adapter.js:77 ORIGINAL EXCEPTION: TypeError: Cannot read property 'availabilties' of undefined
Ответы
Ответ 1
Здесь пример
// 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>
Ответ 2
Кто нибудь тоже спотыкается за этот пост.
Я верю, это правильный путь:
<div *ngFor="let appointment of (_nextFourAppointments | async).availabilities;">
<div>{{ appointment }}</div>
</div>
Ответ 3
Как я могу справиться с этим в шаблоне. каждый раз, когда новый объект помещается в массив, мой цикл повторяется
// 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>
пожалуйста любые предложения