'Why observer method is called twice?
I have the following method that returns observer, but it is called twice:
public getClassesAndSubjects(school: number, whenDate: string): Observable<ClassesAndSubjects[]> {
console.log('1');
const observable = this.classService.GetClassesAndSubjects(school, whenDate);
console.log("2");
observable.subscribe(data => {
if (!data.hasOwnProperty('errors')) {
this.classesSubjects = data;
}
}, error => {
console.log("ERROR loading GetClassesAndSubjects: " + error);
});
console.log("3");
return observable;
}
I mean a line const observable = this.classService.GetClassesAndSubjects(school, whenDate); is called twice and send two times request to server.
Call this like:
this.classInstance.getClassesAndSubjects(school, date).subscribe(value => {
// TODO
});
Solution 1:[1]
Unlike Promises, Observable's functions are called when subscribed to, not when created. Each subscription to an Observable will cause the Observable's function to be run again.
If you want to share one Observable's emission with multiple Subscribers, use share(). Otherwise, if you just want to tag functionality on emissions without subscribing to the Observable, you can use do() (or tap for RxJS 5+).
Solution 2:[2]
You are having trouble because you are subscribing to the same method in two places.
// Your code that is subscribing to the events in two different places, which is why it is called twice.
/*public getClassesAndSubjects(school: number, whenDate: string): Observable<ClassesAndSubjects[]> {
console.log('1');
const observable = this.classService.GetClassesAndSubjects(school, whenDate);
console.log("2");
observable.subscribe(data => {
if (!data.hasOwnProperty('errors')) {
this.classesSubjects = data;
}
}, error => {
console.log("ERROR loading GetClassesAndSubjects: " + error);
});
console.log("3");
return observable;
}*/
import { tap, catchError } from 'rxjs/operators';
import { Observable } from 'rxjs/Observable';
public getClassesAndSubjects(school: number, whenDate: string): Observable<ClassesAndSubjects[]> {
return this.classService.GetClassesAndSubjects(school, whenDate)
.pipe(
tap(data => this.classesSubjects = !data.hasOwnProperty('errors') ? data : this.classesSubjects),
catchError(err => {
console.log("ERROR loading GetClassesAndSubjects: " + error);
return Observable.throw(err);
})
);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | joh04667 |
| Solution 2 | th3n3wguy |
