Joe Joe - 1 year ago 229
TypeScript Question

Cant get Observable of string value (angular2/typescript)

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() {
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?


If you need it, this is updateListNewOrder(...):

public updateListNewOrder(newOrderedList: string[]): Observable<ServerResponse> {
let apiURL = "my/api/url";
return, JSON.stringify(newOrderedList), { headers: this.defaultHeaders() }

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download