Cannot read property 'isStopped' of undefined [Angular2]

5.2k views Asked by At

I'm trying to use an observable for my service in Angular 2.

But I'm receiving this error:

Uncaught TypeError: Cannot read property 'isStopped' of undefined

A sneak peek of my service:

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

@Injectable()

export class Service{

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

}

And the implementation:

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");
      }
    );
  }

}

Did anyone had this error? I couldn't find anything related.

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

EDIT:

Sorry this is where the "isStopped" is coming from: https://github.com/ReactiveX/rxjs/blob/master/src/Subscriber.ts#L94

From the rxjs library.

2

There are 2 answers

0
Gaspar Err. On BEST ANSWER

It seems I was using a callback as a parameter inside the observable at certain point and removing that fixed the problem. I still don't understand why but I'm guessing it has to do something with how Observables work.

0
dsapalo On

To add more clarity to this problem, I've provided a JSFiddle that demonstrates and explains the problem.

Problematic code

The following will throw the error:

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

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

Correct code

To retain the proper scope that is expected of the subscriber.error method of the subscriber object, you must create an anonymous function:

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

A Typescript example is demonstrated in the JS section of this JS Fiddle.

Further readings

You Don't Know JS: Scope & Closures