Recently, I came across a concerning issue in my Angular 5 App.
It all started with this simple call in my service:
interface U{
name:string;
}
...
constructor(private http : *Http*, private httpC:HttpClient) // Http is deprecated - its a compare test
...
ping() //Test Debug func
{
let o:Observable<U> = this.httpC.get<U>(this.url + "user/1");
o.subscribe(resp => {
console.log("SUBSCRIBE1: Init:get:user:U: " + resp.name);
return resp;
},
this.handleError);
o.subscribe(resp => {
console.log("SUBSCRIBE2: Init:get:user:U: " + resp.name);
return resp;
},
this.handleError);
o.toPromise().then(resp => {
console.log("PROMISE: Init:get:user:U: " + resp.name);
return resp;
});
}
Upon calling the ping() function, the Angular/Browser seems to be making three separate calls to "url/user/1" One for each listener (2 subscribes, 1 promise)
Is this normal behavior?
I always thought an Observer allows multiple "Listeners" to wait for an action, not trigger it.
Can someone please provide some clarity or an example of how to handle this situation correctly? Any guidance would be greatly appreciated!
EDIT: Adding further experimentation with a similar call using the deprecated HTTP client yields the same results. It appears to be intentional design. However, I'm still unsure of how to listen without triggering multiple calls.
ping() //Test Debug func
{
let o:Observable<U> = this.httpC.get<U>(this.url + "user/1");
o.subscribe(resp => {
console.log("SUBSCRIBE1: Init:get:user:U: " + resp.name);
console.log(resp);
//this.currentUser = resp;
return resp;
},
this.handleError);
o.subscribe(resp => {
console.log("SUBSCRIBE2: Init:get:user:U: " + resp.name);
console.log(resp);
//this.currentUser = resp;
return resp;
},
this.handleError);
o.toPromise().then(resp => {
console.log("PROMISE1: Init:get:user:U: " + resp.name);
console.log(resp);
//this.currentUser = resp;
return resp;
});
o.toPromise().then(resp => {
console.log("PROMISE2: Init:get:user:U: " + resp.name);
console.log(resp);
//this.currentUser = resp;
return resp;
});
let call:string = this.url + "user/1";
return this.http.get(call)
.toPromise()
.then(resp => {
console.log("OLD HTTP PROMISE 1 " + resp);
return resp;
})
.catch(this.handleError)
.then(resp => {
console.log("OLD HTTP PROMISE 2 " + resp);
return resp;
});
}
The network activity shown by Chrome after a single ping call can be seen here: