无法读取未定义 [Angular2] 的 属性 'isStopped'

Cannot read property 'isStopped' of undefined [Angular2]

我正尝试在 Angular 2.

中为我的服务使用 observable

但是我收到这个错误:

Uncaught TypeError: Cannot read property 'isStopped' of undefined

先睹为快我的服务:

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

@Injectable()

export class Service{

  getList(){
    return new Observable((observer)=>{
      observer.next(result);
    })
  }

}

和实施:

import ...

@Component({...})

export class List implements OnInit {
  list : any[];
  list$ : Observable<Array<any>>;

  constructor(...){
  }

  ngOnInit(){
    this.list$ = this.Service.getList();
    this.list$.subscribe(
      (items) => {
        this.list = items;
        console.log("triggered");
      },
      (error)=>{
        console.error(error);
      },
      ()=>{
        console.log("completed");
      }
    );
  }

}

有人遇到过这个错误吗?我找不到任何相关内容。

============================================= ===================

编辑:

抱歉,这是 "isStopped" 的来源: https://github.com/ReactiveX/rxjs/blob/master/src/Subscriber.ts#L94

来自 rxjs 库。

似乎我在某个时候使用回调作为可观察对象内部的参数,然后删除它解决了问题。我仍然不明白为什么,但我猜它必须与 Observables 的工作方式有关。

为了更清楚地说明这个问题,我提供了 a JSFiddle 来演示和解释这个问题。

有问题的代码

以下将抛出错误:

Uncaught TypeError: Cannot read property 'isStopped' of undefined.

somePromise
  .then(result => {
    subscriber.next(result);
    subscriber.complete();
  })
  .catch(subscriber.error);

正确的代码

要保留订阅者对象的 subscriber.error 方法所期望的适当范围,您必须创建一个匿名函数:

  somePromise
  .then(result => {
    subscriber.next(result);
    subscriber.complete();
  })
  .catch((error) => subscriber.error(error));

本 JS 的 JS 部分演示了一个 Typescript 示例 Fiddle。

进一步阅读

You Don't Know JS: Scope & Closures