I have a function that gets a list of objects and POSTs it to an api.
The function returns Observable since who ever calls it expects to get a string back from it based on the api response.
If the response is good I want to return a certain string and if it is error I want to send a different string.
This is my function that returns a string:
public sendUpdate(updatedList: Cars[]): Observable<string> {
return this._myService.updateListNewOrder(updatedList)
.map(response => "The POST worked successfully")
.catch(error => Observable.of("An Error occurred"));
}
So now I want to call this function and get the string in my component.ts:
messageToDisplay: string;
public updateList() {
this._myService.sendUpdate(this.listToUpdate).subscribe(
res => this.messageToDisplay = res, // onNext
error => this.messageToDisplay = error // onError
);
}
but this is not working...I don't get errors. It is just that the messageToDisplay is staying undefined.
Does anyone see the problem?
Thanks!
If you need it, this is updateListNewOrder(...):
public updateListNewOrder(newOrderedList: string[]): Observable<ServerResponse> {
let apiURL = "my/api/url";
return this.http.post(apiURL, JSON.stringify(newOrderedList), { headers: this.defaultHeaders() }
);
}
I reproduced your logic here with my own functions and everything worked fine. Your sendUpdate
method seems to be correct as well as the subscribe
function. So, the RxJS logic is ok for me. The problem might be in another peace of code that isn't exposed.
The only issue I found out was the type of the updateListNewOrder
. It should be Observable<Response>
instead of Observable<ServerResponse>
if you are using the @angular/http
module.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With