Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);

}

like image 365
Noob Avatar asked Mar 13 '26 18:03

Noob


1 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);
});
like image 122
Aakriti.G Avatar answered Mar 16 '26 09:03

Aakriti.G



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!