Angularjs   发布时间:2022-04-20  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了typescript – 使用带有ngFor和Async Pipe Angular 2的Observable Object中的数组大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图了解如何在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
这是一个例子
// 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>

大佬总结

以上是大佬教程为你收集整理的typescript – 使用带有ngFor和Async Pipe Angular 2的Observable Object中的数组全部内容,希望文章能够帮你解决typescript – 使用带有ngFor和Async Pipe Angular 2的Observable Object中的数组所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。