Issue
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
this is happening because you subscribe to the observable twice, and observables execute every time they're subscribed to.
change this:
observable.subscribe(data => {
if (!data.hasOwnProperty('errors')) {
this.classesSubjects = data;
}
}, error => {
console.log("ERROR loading GetClassesAndSubjects: " + error);
});
to this:
observable.do(data => {
if (!data.hasOwnProperty('errors')) {
this.classesSubjects = data;
}
});
this way you're just adding an operator onto your stream that won't execute till you subscribe to it in your return.
Answered By - bryan60
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.