10

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"?

Øystein Amundsen
  • 3,993
  • 8
  • 44
  • 63

1 Answers1

14

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.

AndreaM16
  • 3,917
  • 4
  • 35
  • 74
  • 3
    Your understanding is partially wrong. There is indeed a lettable version of the catch operator, called catchError, but the original still exists. In the same blog that you linked, there is an example that uses the old patch approach with no problems, and it matches OPs implementation. So refactoring OPs approach to use the new pipe method, doesnt really answers his question. – Jota.Toledo Nov 21 '17 at 12:35
  • You are right. I proposed a way to solve it with lettable operators. – AndreaM16 Nov 21 '17 at 12:56