将可观察对象中的数组与ngFor和Async Pipe Angular 2一起使用


91

我试图了解如何在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)

我在要显示的组件中以可观察的形式订阅它:

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

实际的错误消息是什么?
君特Zöchbauer

编辑添加错误
C. Kearns

最新的angular-rc1语法为*ngFor="let appointment of _nextFourAppointments.availabilities | async">
Jagannath,2016年

这是对的,但不会引起错误。它只是抛出一个警告。
C. Kearns

3
我相信某处有错字。错误信息指出availabilties应该有availabilities
Ivan Sivak

Answers:


152

这是一个例子

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

我的get函数虽然返回一个主题: public _appointmentChoices: Subject<any> = new Subject() getAppointments() { return this._appointmentChoices.map(object=>object.availabilities).subscribe() } ,当我将其设置为相等时,在控制器中我收到错误:browser_adapter.js:77Error: Invalid argument '[object Object]' for pipe 'AsyncPipe',如何将主题变成可观察的?
C. Kearns

public _appointmentChoices: Subject<any> = new Subject() getAppointments() { return (this._appointmentChoices.map(object=>object.availabilities).asObservable()) } } 这给了我错误:property asObservable does not exist on type observable,但是_appointmentChoices是一个Subject
C. Kearns

这已经是一个可观察的!我只需要订阅它!
C. Kearns

我在整合主题方面还有另一个问题。这是使用可观察对象和主题的StackBlitz
IceWarrior353 '18

12

谁也偶然发现了这个帖子。

我相信是正确的方法:

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

1

我想你在找什么

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


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

除了scan运营商,您还可以使用.pipe(toArray())
MotKohn

创建自己的另一个陷阱Subject是不打电话complete()。累加器将永远不会运行。
MotKohn
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.