【发布时间】:2019-01-12 05:16:03
【问题描述】:
我有这个代码sn-p:
SubmitTransaction(transNumber: string, transactionRequest: ITransactionRequestObj): Observable<TransactionResponse> {
this.body = JSON.stringify(transactionRequest);
this.headers = new HttpHeaders().set('Content-Type', 'application/json');
this.headers.append('Accept', 'application/json');
this.options = new RequestOptions({headers: this.headers});
return this.http.post<TransactionResponse>(this.baseUrl + '/transactions/' + transNumber + '/new', this.body, this.options)
.pipe(catchError((e) => this.errorHandler(e)));
}
我所做的只是将我的项目从 Angular 5 升级到 Angular 6 并将 .catch((e) => this.errorHandler(e)); 更改为 .pipe(catchError((e) => this.errorHandler(e))); 。但是,对于此特定方法,我收到以下 TypeScript 错误。
错误:
[ts]
Type 'Observable<HttpEvent<TransactionResponse>>' is not assignable to type 'Observable<TransactionResponse>'.
Type 'HttpEvent<TransactionResponse>' is not assignable to type 'TransactionResponse'.
Type 'HttpSentEvent' is not assignable to type 'TransactionResponse'.
Property '_transactionNumber' is missing in type 'HttpSentEvent'.
我不确定在这种情况下我应该做什么。上面的代码 sn-p 在 Angular 5 中工作。我需要做什么才能为 Angular 6 修复它?
编辑:
errorHandler(error: HttpErrorResponse) {
return throwError(error.message || 'Server Error');
}
我注意到如果我不使用 HttpHeaders,它可以工作:
SubmitTransaction(transNumber: string, transactionRequest: ITransactionRequestObj): Observable<TransactionResponse> {
this.body = JSON.stringify(transactionRequest);
this.headers = new HttpHeaders().set('Content-Type', 'application/json');
this.headers.append('Accept', 'application/json');
this.options = new RequestOptions({headers: this.headers});
return this.http.post<TransactionResponse>(this.baseUrl + '/transactions/' + transNumber + '/new', transactionRequest)
.pipe(catchError((e) => this.errorHandler(e)));
}
但是,我可能需要使用 HttpHeaders...在这种情况下,解决方法是什么?
【问题讨论】:
-
请发布您的errorHandler代码
-
@firegloves 已编辑帖子。
-
我认为 HttpHeaders 是不可变的,你应该将一些 set 方法链接在一起而不是 append
-
使用 Angular 6 / RxJs 6,没有必要在请求体上使用 JSON.stringify()。添加到上述响应中,标头是不可变的,因此每次调用 append 都会返回一个新的标头对象实例。您在函数调用中创建的大多数实例并不是真正必需的。你这样做有什么特别的原因吗?您是否尝试缓存这些变量以供以后使用?
标签: angular typescript angular6 rxjs6