3

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 2

1

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);
});
Sign up to request clarification or add additional context in comments.

7 Comments

I get this error. NodeInvocationException: Unexpected token R in JSON at position 0 SyntaxError: Unexpected token R in JSON at position 0
console data only instead of parsing it in JSON and check what are you getting in the response
If we are not returning any JSON object then angular throws an Unexpected token (any alphabet) in JSON at position 0 at JSON.parse () exception.
console.log(data) works...i get my expected value. however, the subscribe bit is not working...it is an async call, so assigning to a local variable is not executing that code. var retval: ""; this.service.getCustomerName(value).subscribe( data => { console.log(data); // this works retval = data; }, error => { console.log(error); }); return retval; //undefined here
You can use a global variable for that
|
0

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

2 Comments

for got to mention, in the component there is a function that calls another function in the service. So its like component function getData would call service.getdata.subscribe(data=>console.log(data))
Does it even work? I get error message that *Property 'map' does not exist on type 'Observable<Object>...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.