【问题标题】:Cannot read property 'isStopped' of undefined [Angular2]无法读取未定义 [Angular2] 的属性“isStopped”
【发布时间】:2017-01-04 22:01:43
【问题描述】:

我正在尝试在 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 库。

【问题讨论】:

标签: javascript angular observable subscriber


【解决方案1】:

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

有问题的代码

以下会抛出错误:

未捕获的类型错误:无法读取未定义的属性“isStopped”。

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 Fiddle 的 JS 部分演示了一个 Typescript 示例。

进一步阅读

You Don't Know JS: Scope & Closures

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2017-12-15
      • 2017-06-18
      • 1970-01-01
      • 2017-02-06
      • 2017-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多