typescript - example - Uso de una matriz de objetos observables con ngFor y Async Pipe Angular 2
async pipe example (1)
Estoy tratando de entender cómo usar Observables en Angular 2. Tengo este servicio:
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));
}
}
Este BehaviorSubject recibe nuevos valores de otro servicio:
that._appointmentChoiceStore._appointmentChoices.next(parseObject)
Me suscribo en forma de un observable en el componente en el que quiero mostrarlo:
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
})
}
}
Y el intento de mostrar en la vista así:
<li *ngFor="#appointment of _nextFourAppointments.availabilities | async">
<div class="text-left appointment-flex">{{appointment | date: ''EEE'' | uppercase}}
Sin embargo, las disponibilidades aún no son una propiedad del objeto observable, por lo que se equivoca, incluso aunque lo defina en la interfaz de disponibilidades de la siguiente manera:
export interface Availabilities {
"availabilities": string[],
"length": number
}
¿Cómo puedo mostrar una matriz de forma asíncrona desde un objeto observable con la tubería asíncrona y * ngFor? El mensaje de error que recibo es:
browser_adapter.js:77 ORIGINAL EXCEPTION: TypeError: Cannot read property ''availabilties'' of undefined
Aquí hay un ejemplo
// 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>