Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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() {
      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() }
    );
  }
like image 729
Joe Avatar asked Aug 03 '16 22:08

Joe


1 Answers

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.

like image 102
Bernardo Pacheco Avatar answered Nov 08 '22 06:11

Bernardo Pacheco