I have this code snippet:
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)));
}
where all I did was upgrade my project from Angular 5 to Angular 6 and change .catch((e) => this.errorHandler(e));
to .pipe(catchError((e) => this.errorHandler(e)));
. However, I am getting the following TypeScript error for this particular method.
Error:
[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'.
I'm not sure what I should do in this scenario. The code snippet above was working in Angular 5. What do I need to do to fix it for Angular 6?
EDIT:
errorHandler(error: HttpErrorResponse) {
return throwError(error.message || 'Server Error');
}
I have noticed if I don't use the HttpHeaders, it works:
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)));
}
However, I might need to use the HttpHeaders... what is the workaround in this scenario?
HttpHeaders
is an immutable data structure.
The method append
returns a new instance of HttpHeaders
rather than mutating the existing one, meaning you'll need to make a tiny change in your code.
// old
this.headers.append('Accept', 'application/json')
// new
this.headers = this.headers.append('Accept', 'application/json')
Even better, just do it all at once:
this.headers = new HttpHeaders()
.set('Content-Type', 'application/json')
.set('Accept', 'application/json')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With