How to return string instead of Observable with @angular/http

Viewed 9267

I am hooking Angular 4 with .net core WEB API.

The Web API is returning a CustomerName in string based on the Id passed in.

This is the service method in Angular 4. I understand that angular/http must return an Observable because it is an Async call.

But how do I return a string instead? or how do I access the data within the Observable object from the calling method?

    getCustomerName(id: number): Observable<any>{
return this._http.get(this.baseUrl + 'api/getCustomerName/' + id )
    .map((response: Response) => <any>response.json() )
    .catch(this.handleError);

}

2 Answers

To access data from observable, in your service return the response you get from the api like this:

getCustomerName(id: number): Observable<any>{
     return this._http.get(this.baseUrl + 'api/getCustomerName/' + id );
   }

and in your component call the method of the service as:

getCustomerName(id).subscribe(
   data => {
   console.log(JSON.parse(data));
},
error => {
   console.log(error);
});

use this function with a map operator:

private extractData(res) {
    let body = res.json();  // If response is a JSON use json()
    if (body) {
        return body.data || body;
    } else {
        return {};
    }
}

and in the service use map like this:

return this.http.post(url, body, options)
        .map(this.extractData)

If its not a json then simply omit the parsing line

Related