Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Observable .catch is not a function

I get this very annoying error when running my code from a unix environment. This works fine when I run the code locally through ng serve, But when I deploy the code to my server, this error halts all program execution:

ERROR TypeError: this.http.get(...).catch is not a function

Google results state that I should import rxjs namespaces straight from their location, and not through the rxjs/Rx bundle, but I get this error regardless. Other results point out that I may have missed importing rxjs operators, but they are definitely included in my case.

I've even checked the included sourcemaps using DevTools, and the operators are included out to the browser.

Can anybody tell me why I'm getting this error? I'm using rxjs: ^5.5.2

This is my code.

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';

@Injectable()
export class MyService {
  constructor(private http: HttpClient) {}

  all(): Observable<any> {
    return this.http.get<any>('url')
      .catch(err => this.handleError(err));
  }
  handleError(error) {
    return Observable.throw(error);
  }
}

EDIT Based on @Jota.Toledo's comment below, I will provide the code using this method:

this.myService.all().subscribe(
  result => {
    this.isLoading = false;
    if (result) {
      this.clients = result;
    }
  },
  error => this.isLoading = false
);

Is giving two callback functions in subscribe like this, the same as "using the catch method somewhere before the operator is added"?

like image 787
Øystein Amundsen Avatar asked Nov 21 '17 11:11

Øystein Amundsen


1 Answers

In rxjs 5.5.2 you can solve this problem using lettable operator, in this case, catchError. You have to import it from operators like: import { catchError } from 'rxjs/operators/catchError';. In general, all operators must be imported in this way, same thing goes for observable like observable/of.

import { catchError } from 'rxjs/operators/catchError';
import { map } from 'rxjs/operators/map';

all(): Observable<any> {
  return this.http.get<any>('url')
    .pipe(
        map(() => //do stuff),
        catchError((error: Error) => {
         //
        })
    )
}

Read more about lettable operators here.

like image 88
AndreaM16 Avatar answered Nov 02 '22 11:11

AndreaM16