Reputation: 99
I have an interesting issue that I can't seem to resolve. My application uses HTTP calls to various endpoints and the majority of them work with no issues. There is one in particular that is causing me a headache and is probably the simplest of them all.
I have a service which contains a function that has a return value that looks like the following.
return this._http.post(this.baseEndPoint + this.uri, postc, options)
.map(res => res.json());
Which, to me, is pretty standard. What's strange is that on any error response/code, the code in my success/complete function is being executed and on any successful response, the code in my error function is being executed. The responses from the API come back as a 404 and 204 so I would expect they be caught accordingly.
this._service.function(param, param1)
.subscribe(
error => {
console.log(error);
},
() => {
console.log('lol wut');
}
);
There's nothing special here at all. Also, I'm noticing that my requests are making two network calls, one being initiated by polyfills which shows successful with a status of 200 but then it's followed by another call with a status of 404 triggered by "other."
So, my questions are — why are these reversed? How do I resolve that and allow them to be caught in appropriate place? Why are there two calls being made?
Upvotes: 0
Views: 34
Reputation: 1456
You are seeing two network requests because of Request OPTIONS , Angular makes a preflight HTTP OPTIONS request because of cross origin nature of request. https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS. Also , your callbacks are written in wrong order
this._service.function(param, param1)
.subscribe(
error => { // DONT CONFUSE with the name error, it can be any //name
console.log(error);
},
() => {
console.log('lol wut');
}
);
Here , the first argument method is called upon success , 2nd on error and third is info I think. Actual callbacks should be
this._service.function(param, param1)
.subscribe(
data=>{
console.log("status code is ",data.status);},
error => {
console.log(error);
},
() => {
console.log('lol wut');
}
);
Or as per your need.
Upvotes: 1
Reputation: 706
I'm not sure why you are seeing two network requests, but based on your argument names, I think you have your callbacks reversed? subscribe
's first argument can be a function that will execute on next
notifications on a stream, the second argument will be invoked on error
notifications. The third is for completion notifications.
this._service.function(param, param1).subscribe( onNext, onError, onComplete );
If order is a problem, you can also provide an object to subscribe which implements the observer interface, like so:
this._service.function(param, param1).subscribe({
next: x => console.log( x ),
error: x => console.error( x ),
complete: () => console.info( 'done!' ),
});
Upvotes: 1