Cannot read property "next" of undefined

I subscribe to an observable so anytime my call subscribeToTasks()

in my service fails, it will end up calling the code in my method subscriptionError()

from my component, which in this example is just a simple warning. The problem is that whenever an error occurs in this call and is called this.newSubscriptionFailure.next()

, I get the following error in the browser console:

Cannot read property "next" of undefined

How newSubscriptionFailure

undefined when you can clearly see that it is defined above the method? This code should get hit long before the api call error occurs. I've used this approach in the past and it has always worked, the only difference I can think of is what I call .next()

in the service (the same file as newSubscriptionFailure

), whereas I usually call .next()

in a separate component file. What am I doing wrong? Is there a way I can get this to work, or a better approach?

Code from my service:

import { Observable } from 'rxjs/Observable';
import { Subject }    from 'rxjs/Subject';

public subscribeToTasks(period: string, stripeToken: string): Observable<any> {        
    let body = JSON.stringify({ period, stripeToken });
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });        
    return this.authHttp.post(this.apiTasks, body, options).map(response => {
        return response.json();
    }).catch(this.newSubscriptionError);
}


newSubscriptionFailure = new Subject();
newSubscriptionFailure$ = this.newSubscriptionFailure.asObservable();

public newSubscriptionError() {
    this.newSubscriptionFailure.next();
}

      

code from my component:

ngOnInit(): void {
    this.subscriptionError();
}

subscriptionError(){
    this.subscriptionsService.newSubscriptionFailure$.subscribe(() => {
        alert('call failed');
    });
}

      

+3


source to share


2 answers


Edit

}).catch(this.newSubscriptionError);

      

to

}).catch((e)=>this.newSubscriptionError());

      



or

}).catch(this.newSubscriptionError.bind(this));

      

yours this

does not refer to Injectable

otherwise

+6


source


If anyone else has the same problem as me. I used a theme called this.destroy $ which I call further in the OnDestroy method. Using it signed observed, for example .takeUntil(this.destroyed$)

. I forgot to initialize this destroy object. After using it, the destroy$: Subject<any> = new Subject<any>();

error disappeared.



0


source







All Articles