我正在开发一个带有离子3 /角度的应用程序,我遇到了一个小问题。我正在服务中发出一个帖子请求,我正在尝试使用成功回调的返回值。 我得到以下转换错误:
Argument of type 'ArrayBuffer' is not assignable to parameter of type 'Occasion'. Property 'id' is missing in type 'ArrayBuffer'.
导致错误的代码:
this.api.post('occasions', occasion).subscribe(occasion => {
this.myOccasions.unshift(occasion);
this.myOccasionsChanged.next(this.myOccasions);
},
列表this.myOccasions
定义为private myOccasions: Occasion[];
我的api服务帖子功能定义为:
post(endpoint: string, body: any, reqOpts?: any) {
if (!reqOpts) {
reqOpts = {};
}
let headers = {};
this.addAccessTokenToHeaders(headers);
reqOpts.headers = headers;
return this.http.post(this.url + '/' + endpoint, body, reqOpts);
}
你能告诉我有关如何使这些类型达成一致的任何建议吗?当然,我的POST端点返回一个OccasionDto来使用。 干杯!
答案 0 :(得分:1)
你可以映射.post()方法来转换数据并返回你需要的东西(一个场合)
post(endpoint: string, body: any, reqOpts?: any): Observable<Occasion> {
//etc...
return this.http.post(this.url + '/' + endpoint, body, reqOpts);
.map( data => {
//do some transformation in the data, to return an `Occasion`
const newData = /* something here, a function, a new Occasion(args), etc.... */
return newData;
})
}
答案 1 :(得分:0)
我找到了问题的答案。我处理它的方式如下:
在我的ApiService中,我更改了方法签名,以便他们需要指定预期的返回类型并将响应类型设置为'json',因为根据angular docs,http客户端将返回Observable<Object>
。< / p>
post<T>(endpoint: string, body: any): Observable<T> {
return this.http.post<T>(this.url + '/' + endpoint, body, {responseType:
'json'});
}
然后,当我调用我的apiService方法时,我指定了我想要的实体,如下所示:
this.api.post<Occasion>('occasions', occasion).subscribe(result => {
this.myOccasions.unshift(result);
this.myOccasionsChanged.next(this.myOccasions);
},
我认为它非常整洁,但如果有人有更清洁/更好的东西,请分享:)