it-source

ngFor 및 Async Pipe Angular 2를 사용한 관찰 가능한 오브젝트로부터의 배열 사용

criticalcode 2023. 4. 6. 21:46
반응형

ngFor 및 Async Pipe Angular 2를 사용한 관찰 가능한 오브젝트로부터의 배열 사용

Angular 2에서 Observatibles를 사용하는 방법을 이해하려고 합니다.다음과 같은 서비스가 있습니다.

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));
    }
}

이 Behavior Subject는 다른 서비스에서 새로운 값으로 푸시됩니다.

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>

네가 찾는 건 이거인 것 같아

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

어레이가 없지만 관찰 가능한 것을 어레이처럼 사용하려는 경우 개체 스트림이지만 기본적으로 작동하지 않습니다.아래에서는 개체를 삭제하는 것이 아니라 관찰 가능한 개체에 추가하는 데만 신경을 쓴다고 가정하여 이 문제를 해결하는 방법을 보여 줍니다.

소스가 BehaviorSubject 유형인 관찰 가능을 사용하려는 경우 이를 ReplaySubject로 변경한 다음 구성 요소에서 다음과 같이 구독합니다.

요소

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

HTML

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

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

반응형