类型错误undefined不是对象

时间:2017-08-31 16:26:11

标签: javascript angular typescript typeerror server-sent-events

我正在尝试创建一个Server Sent Event类,它将观察其他组件并向他们发送信息,但是当我尝试订阅我的observable时我遇到了错误。

这是我的Server Sent Event类:

@Injectable()
export class ServerSentEvent implements OnInit{
  public observable : Observable<any>;
  ngOnInit(){
    var errorCount = 0;
    this.observable = Observable.create(observer => {
      var eventSource = new EventSource(filterUrl);
      eventSource.onmessage = (event: any)=>{
        console.log("received val: " + JSON.parse(JSON.parse(event.data).payload).value);
        observer.next(JSON.parse(JSON.parse(event.data).payload).value);
      }
      eventSource.onerror=(error: any)=>{
        errorCount++;
        if(error.targer.readyState === 0 && errorCount > 5){
          eventSource.close();
          observer.error();
        }
      }
      return() => {
        eventSource.close();
      };
    });
  }
}

这是我的lightControler类:

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers:[ServerSentEvent]
})
export class LightControler implements OnInit{
  connected : boolean;
  light : boolean;
  public button = (<HTMLInputElement>document.getElementById("check-toggle"));
  public slider = (<HTMLInputElement>document.getElementById("light-slide"));
  public slid = (<HTMLProgressElement>document.getElementById("light-bar"));

  public constructor(
    private http : HttpClient,
    private serverSentEvent: ServerSentEvent){
    this.serverSentEvent.observable.subscribe(
      {
        next: val =>{
          console.log("light val: "+ val);
          this.slid.value = val;
          if (val >= 1){
            this.light = true;
            this.button.checked = true;
          }
          else{
            this.light = false;
            this.button.checked = false;
          }
        },
        error: error =>{
          setTimeout(()=> serverSentEvent.ngOnInit(), 1000);
        }
      }
    );
  }

错误发生在this.serverSentEvent.observable.subscribe()

  

TypeError:undefined不是对象(评估   'this.serverSentEvent.observable.subscribe')

有谁知道如何解决这个问题或者我做错了什么?

修改

当lightControler的构造函数是因为我试图订阅一个不存在的observable时,ServerSentEvent的ngOnInit没有启动。

我需要在订阅observable之前调用serverSentEvent.ngOnInit()。

1 个答案:

答案 0 :(得分:0)

您正在将对象传递给订阅函数,而不是函数。尝试像这样更改代码:

this.serverSentEvent.observable.subscribe(
  val => {
      console.log("light val: "+ val);
      this.slid.value = val;
      if (val >= 1){
        this.light = true;
        this.button.checked = true;
      }
      else{
        this.light = false;
        this.button.checked = false;
      }
    },
    error => {
      setTimeout(()=> serverSentEvent.ngOnInit(), 1000);
    });