Development Tip

ngFor 및 Async Pipe Angular 2와 함께 Observable Object의 배열 사용

yourdevel 2020. 10. 29. 20:08
반응형

ngFor 및 Async Pipe Angular 2와 함께 Observable Object의 배열 사용


Angular 2에서 Observable을 사용하는 방법을 이해하려고합니다.이 서비스가 있습니다.

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
}

비동기 파이프 및 * ngFor를 사용하여 관찰 가능한 개체에서 비동기 적으로 배열을 표시하려면 어떻게해야합니까? 내가 얻는 오류 메시지는 다음과 같습니다.

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

여기에 예가 있습니다.

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

이 게시물을 우연히 발견 한 사람.

나는 올바른 방법이라고 믿습니다.

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

참고URL : https://stackoverflow.com/questions/37669871/using-an-array-from-observable-object-with-ngfor-and-async-pipe-angular-2

반응형