使用异步管道时无法读取未定义的属性“ next”

时间:2018-12-06 04:20:06

标签: angular rxjs observable angular2-observables

我有这样的服务,它可以模拟API调用,

import { Injectable } from '@angular/core';
import { Observable, Subscriber} from 'rxjs';

import { DeviceStatus } from '../models/device-status-model';

@Injectable()
export class GetStatusService {
  public deviceStatusObserver: Subscriber<DeviceStatus>;
  public deviceStatus: Observable<DeviceStatus>;

  constructor() { 
    this.deviceStatus = new Observable(observer => {
      this.deviceStatusObserver = observer;
    });
  }

  getRandom(max): number {
    return Math.floor(Math.random() * Math.floor(max));
  }

  callApi() {
    setInterval(() => {
      //Mocking data
      let status = new DeviceStatus();
      status.tempC = this.getRandom(50) + 'C';
      status.tempF = this.getRandom(50) + 'F';
      status.humidity = this.getRandom(100) + '%';
      status.pin1 = true;
      status.pin2 = true;
      status.pin3 = true;
      status.pin4 = true;
      this.deviceStatusObserver.next(status);
    }, 500);
  }
}

还有这样的组件

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';


import { GetStatusService } from '../services/get-status.service';
import { DeviceStatus } from '../models/device-status-model'

@Component({
  selector: 'app-layout',
  templateUrl: './layout.component.html',
  styleUrls: ['./layout.component.css']
})
export class LayoutComponent implements OnInit {

  dStatus$: Observable<DeviceStatus>;

  humidityValue: string; tempValue: string;

  constructor(private getStatusService: GetStatusService) { 
    this.dStatus$ = getStatusService.deviceStatus;
  }

  ngOnInit() {
     this.getStatusService.deviceStatus.subscribe((data) => {
       this.tempValue = data.tempC;
       this.humidityValue = data.humidity;
     });
    this.getStatusService.callApi();
  }
}

我想将此Observable与异步管道一起使用,所以我删除了

this.getStatusService.deviceStatus.subscribe((data) => {
           this.tempValue = data.tempC;
           this.humidityValue = data.humidity;
         });

然后我开始在控制台上获得ERROR TypeError: Cannot read property 'next' of undefined。 即使我使用异步管道,我也需要订阅Observable吗?我查找的所有教程都没有使用订户方法。

链接到StackBlitz中的项目

1 个答案:

答案 0 :(得分:0)

最后弄清楚了,

changed在callApi()中添加了空支票

  callApi() {
    setInterval(() => {
      let status = new DeviceStatus();
      status.tempC = this.getRandom(50) + 'C';
      status.tempF = this.getRandom(50) + 'F';
      status.humidity = this.getRandom(100) + '%';
      status.pin1 = true;
      status.pin2 = true;
      status.pin3 = true;
      status.pin4 = true;
      if(!this.deviceStatusObserver)
        return;
      this.deviceStatusObserver.next(status);
    }, 500);
  }