angular 4 HTTP 客户端转换类型响应
angular 4 HTTP Client casting type response
在我的 angular 4 项目中,我使用的是 HTTP 客户端,当我有一个 GET 调用时,响应有时是明确的,所以我必须做类似的事情:
this.loggedUser.name = response._embedded.agent.name
但在这种情况下我有这个错误:
Property '_embedded' does not exist on type 'HttpResponse'
我通过将响应投射到任何内容来解决问题:
getLoggedUser(url) {
return this.http.get(url, {observe: 'response'})
.map((response) => <any>response);
}
那么,我是否必须对所有响应进行强制转换?
这被认为是好的做法,还是我应该做其他事情?
HttpResponse<T>
class确实没有_embedded
属性。这就是为什么您会收到编译器错误的原因,因为 Typescript 静态键入了您对 HttpResponse<Object>
的响应(泛型类型参数用于响应的 body
属性)。
在这种情况下,将响应投射到 <any>
似乎是一个可行的解决方案,如果您知道随时可以在那里获得 _embedded
道具。不过空检查可能是一个不错的补充。
这里是HttpResponse<T>
打字供参考:
/**
* A full HTTP response, including a typed response body (which may be `null`
* if one was not returned).
*
* `HttpResponse` is a `HttpEvent` available on the response event
* stream.
*
* @experimental
*/
export declare class HttpResponse<T> extends HttpResponseBase {
/**
* The response body, or `null` if one was not returned.
*/
readonly body: T | null;
/**
* Construct a new `HttpResponse`.
*/
constructor(init?: {
body?: T | null;
headers?: HttpHeaders;
status?: number;
statusText?: string;
url?: string;
});
readonly type: HttpEventType.Response;
clone(): HttpResponse<T>;
clone(update: {
headers?: HttpHeaders;
status?: number;
statusText?: string;
url?: string;
}): HttpResponse<T>;
clone<V>(update: {
body?: V | null;
headers?: HttpHeaders;
status?: number;
statusText?: string;
url?: string;
}): HttpResponse<V>;
}
在我的 angular 4 项目中,我使用的是 HTTP 客户端,当我有一个 GET 调用时,响应有时是明确的,所以我必须做类似的事情:
this.loggedUser.name = response._embedded.agent.name
但在这种情况下我有这个错误:
Property '_embedded' does not exist on type 'HttpResponse'
我通过将响应投射到任何内容来解决问题:
getLoggedUser(url) {
return this.http.get(url, {observe: 'response'})
.map((response) => <any>response);
}
那么,我是否必须对所有响应进行强制转换? 这被认为是好的做法,还是我应该做其他事情?
HttpResponse<T>
class确实没有_embedded
属性。这就是为什么您会收到编译器错误的原因,因为 Typescript 静态键入了您对 HttpResponse<Object>
的响应(泛型类型参数用于响应的 body
属性)。
在这种情况下,将响应投射到 <any>
似乎是一个可行的解决方案,如果您知道随时可以在那里获得 _embedded
道具。不过空检查可能是一个不错的补充。
这里是HttpResponse<T>
打字供参考:
/**
* A full HTTP response, including a typed response body (which may be `null`
* if one was not returned).
*
* `HttpResponse` is a `HttpEvent` available on the response event
* stream.
*
* @experimental
*/
export declare class HttpResponse<T> extends HttpResponseBase {
/**
* The response body, or `null` if one was not returned.
*/
readonly body: T | null;
/**
* Construct a new `HttpResponse`.
*/
constructor(init?: {
body?: T | null;
headers?: HttpHeaders;
status?: number;
statusText?: string;
url?: string;
});
readonly type: HttpEventType.Response;
clone(): HttpResponse<T>;
clone(update: {
headers?: HttpHeaders;
status?: number;
statusText?: string;
url?: string;
}): HttpResponse<T>;
clone<V>(update: {
body?: V | null;
headers?: HttpHeaders;
status?: number;
statusText?: string;
url?: string;
}): HttpResponse<V>;
}