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

本秂侑毒 提交于 2020-01-14 19:02:09

问题


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

}


回答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);
});



回答2:


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



来源:https://stackoverflow.com/questions/47427934/how-to-return-string-instead-of-observable-with-angular-http

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!