Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type 'Observable<HttpEvent<>>' is not assignable to type 'Observable<>'

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?

like image 215
Euridice01 Avatar asked Aug 04 '18 16:08

Euridice01


1 Answers

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')
like image 85
Lazar Ljubenović Avatar answered Nov 15 '22 00:11

Lazar Ljubenović