[英]Return multiple values from service to component in angular
I am using httpmodule to load data from backend.我正在使用 httpmodule 从后端加载数据。 when I load data in service, I return it to component but I also want to return status code to component.
当我在服务中加载数据时,我将它返回给组件,但我也想将状态代码返回给组件。
Data
model is already defined and can't change it. Data
model 已定义,无法更改。
getData(offSet, maxResults): Observable<Data> {
return this.http.get(this.url+"?offset="+offSet+"&maxResults="+maxResults);
}
this.dataService.getData(0, this.maxResults).subscribe((data)=>{
this.data = data;
this.total = data.totalCount;
this.pages = Math.ceil(this.total / this.maxResults);
});
I want to get status code from subscribe callback like below我想从订阅回调中获取状态码,如下所示
this.dataService.getData(0, this.maxResults).subscribe((data, status_code)=>{
this.data = data;
this.total = data.totalCount;
this.pages = Math.ceil(this.total / this.maxResults);
});
When doing the HTTP request, you can pass the option observe: 'response'
.在执行 HTTP 请求时,您可以传递选项
observe: 'response'
。 Then instead of the data, a HttpResponse
object is being returned, which also contains the status code:然后,返回的不是数据,而是一个
HttpResponse
object,其中还包含状态代码:
Service:服务:
getData(offSet, maxResults): Observable<HttpResponse<Data>> {
return this.http.get(this.url+"?offset="+offSet+"&maxResults="+maxResults, { observe: 'response' });
}
Component:零件:
this.dataService.getData(0, this.maxResults).subscribe((response)=>{
this.data = response.body;
this.total = response.body.totalCount;
this.pages = Math.ceil(this.total / this.maxResults);
// you can use response.status here
});
By default Angular HttpClient
returns the body of the request.默认情况下 Angular
HttpClient
返回请求的正文。 You should add observe: 'response'
HttpOption
to reach headers, statusCode etc.您应该添加
observe: 'response'
HttpOption
以到达标题、状态代码等。
so, you should change your service.所以,你应该改变你的服务。
getData(offSet, maxResults): Observable<{data: Data, statusCode: number}> {
return this.http.get(this.url+"?offset="+offSet+"&maxResults="+maxResults, {observe: }).pipe(
map((response: HttpResponse<Data>) => {
return {
data: response.body,
statusCode: response.status
}
});
)
}
Now it returns an object which has data
and statusCode
property, so you can reach them as the following;现在它返回一个具有
data
和statusCode
属性的 object ,因此您可以通过以下方式访问它们;
this.dataService.getData(foo,bar).subscribe(response => {
const { data, statusCode } = response;
// do something...
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.