【问题标题】:Using an array from Observable Object with ngFor and Async Pipe Angular 2将 Observable Object 中的数组与 ngFor 和 Async Pipe Angular 2 一起使用
【发布时间】:2016-10-06 19:05:50
【问题描述】:

我正在尝试了解如何在 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

【问题讨论】:

  • 实际的错误信息是什么?
  • 编辑添加错误
  • 最新的 angular-rc1 语法为*ngFor="let appointment of _nextFourAppointments.availabilities | async"&gt;
  • 这是真的,但它不会导致错误。它只是抛出一个警告。
  • 我相信某处有错字。错误显示availabilties 而应该有availabilities

标签: typescript angular rxjs observable


【解决方案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>

【讨论】:

  • 我的 get 函数返回了一个主题:public _appointmentChoices: Subject&lt;any&gt; = new Subject() getAppointments() { return this._appointmentChoices.map(object=&gt;object.availabilities).subscribe() } ,当我将它设置为相等时,在控制器中,我收到错误:browser_adapter.js:77Error: Invalid argument '[object Object]' for pipe 'AsyncPipe',我如何将主题变成可观察的?
  • public _appointmentChoices: Subject&lt;any&gt; = new Subject() getAppointments() { return (this._appointmentChoices.map(object=&gt;object.availabilities).asObservable()) } } 这给了我错误:property asObservable does not exist on type observable,但 _appointmentChoices 是 Subject?
  • 它已经是一个可观察的了!我只需要订阅它!
  • 我在整合主题时遇到了另一个问题。这是一个使用可观察对象和主题的 StackBlitz:stackblitz.com/edit/subject-as-observable-list-example
【解决方案2】:

谁也偶然发现了这篇文章。

我相信是正确的方法:

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

【讨论】:

    【解决方案3】:

    我想你要找的是这个

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

    【讨论】:

      【解决方案4】:

      如果你没有数组,但你试图像数组一样使用你的 observable,即使它是一个对象流,这在本机上是行不通的。我将在下面展示如何解决此问题,假设您只关心将对象添加到可观察对象,而不是删除它们。

      如果您尝试使用其源为 BehaviorSubject 类型的 observable,请将其更改为 ReplaySubject,然后在您的组件中像这样订阅它:

      组件

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

      HTML

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

      【讨论】:

      • 你可以使用.pipe(toArray())而不是scan操作符
      • 创建自己的Subject 时的另一个陷阱是不调用complete()。累加器永远不会运行。
      猜你喜欢
      • 1970-01-01
      • 2017-02-02
      • 1970-01-01
      • 1970-01-01
      • 2016-09-25
      • 2016-06-01
      • 2018-03-04
      • 2018-11-18
      • 2018-05-16
      相关资源
      最近更新 更多