本文介绍了在 ngFor 和 Async Pipe Angular 2 中使用来自 Observable 对象的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想了解如何在 Angular 2 中使用 Observables.我有这个服务:

import {Injectable, EventEmitter, ViewChild} from '@angular/core';从rxjs/Observable"导入{Observable};从rxjs/Subject"导入{Subject};从rxjs/Rx"导入{BehaviorSubject};从 './availabilities-interface' 导入 {Availabilities}@Injectable()导出类 AppointmentChoiceStore {public _appointmentChoices: BehaviorSubject= new BehaviorSubject({可用性":[''],长度":0})构造函数(){}获取约会(){返回 this.asObservable(this._appointmentChoices)}asObservable(主题:主题){return new Observable(fn => subject.subscribe(fn));}}

这个 BehaviorSubject 是从另一个服务推送新值的:

that._appointmentChoiceStore._appointmentChoices.next(parseObject)

我在我想在其中显示的组件中以 observable 的形式订阅它:

从 '@angular/core' 导入 {Component, OnInit, AfterViewInit}从../shared/appointment-choice-service"导入 {AppointmentChoiceStore}从 'rxjs/Observable' 导入 {Observable}从 'rxjs/Subject' 导入 {Subject}从rxjs/Rx"导入{BehaviorSubject};从 '../shared/availabilities-interface' 导入 {Availabilities}声明常量时刻:任何@零件({选择器:我的约会选择",模板:需要('./appointmentchoice-template.html'),样式:[require('./appointmentchoice-style.css')],管道:[自定义管道]})导出类 AppointmentChoiceComponent 实现 OnInit、AfterViewInit {私人_nextFourAppointments:可观察的构造函数(私有_appointmentChoiceStore:AppointmentChoiceStore){this._appointmentChoiceStore.getAppointments().subscribe(function(value) {this._nextFourAppointments = 值})}}

并尝试在视图中显示如下:

 <li *ngFor="#appointment of _nextFourAppointments.availabilities |异步"><div class="text-left assignment-flex">{{appointment |日期:'EEE' |大写}}

但是,可用性还不是 observable 对象的属性,因此它会出错,即使我在可用性接口中这样定义它:

导出接口可用性{可用性":字符串[],长度":数字}

如何使用异步管道和 *ngFor 从可观察对象异步显示数组?我得到的错误信息是:

browser_adapter.js:77 ORIGINAL EXCEPTION: TypeError: 无法读取未定义的属性可用性"
解决方案

举个例子

//在服务中获取车辆(){return Observable.interval(2200).map(i=> [{name: 'car 1'},{name: 'car 2'}])}//在控制器中车辆:Observable>ngOnInit() {this.vehicles = this._vehicleService.getVehicles();}//在模板中<div *ngFor='让车辆的车辆|异步'>{{车辆名称}}

I am trying to understand how to use Observables in Angular 2. I have this service:

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

This BehaviorSubject is pushed new values as so from another service:

that._appointmentChoiceStore._appointmentChoices.next(parseObject)

I subscribe to it in the form of an observable in the component I want to display it in:

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

And the attempt to display in the view as so:

  <li *ngFor="#appointment of _nextFourAppointments.availabilities | async">
         <div class="text-left appointment-flex">{{appointment | date: 'EEE' | uppercase}}

However, availabilities isn't yet a property of the observable object so it errors out, even though I define it in the availabilities interface as so:

export interface Availabilities {
  "availabilities": string[],
  "length": number
}

How can I display an array asynchronously from an observable object with the async pipe and *ngFor? The error message I get is:

browser_adapter.js:77 ORIGINAL EXCEPTION: TypeError: Cannot read property 'availabilties' of undefined
解决方案

Here's an example

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

这篇关于在 ngFor 和 Async Pipe Angular 2 中使用来自 Observable 对象的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 01:55