如何使用@ angular/http返回字符串而不是Observable [英] How to return string instead of Observable with @angular/http
问题描述
我将Angular 4与.net核心WEB API挂钩.
I am hooking Angular 4 with .net core WEB API.
Web API正在根据传入的ID返回字符串形式的CustomerName.
The Web API is returning a CustomerName in string based on the Id passed in.
这是Angular 4中的服务方法. 我知道angular/http必须返回一个Observable,因为它是一个异步调用.
This is the service method in Angular 4. I understand that angular/http must return an Observable because it is an Async call.
但是我该如何返回一个字符串呢? 或如何通过调用方法访问Observable对象中的数据?
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);
}
推荐答案
要访问可观察的数据,请在服务中返回您从api中获得的响应,如下所示:
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);
});
这篇关于如何使用@ angular/http返回字符串而不是Observable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!