Module not found: Error: Can't resolve 'rxjs/add/operator/catch' in 'F:\Angular\HttpServices\http-services\src\app'
Asked Answered
K

7

15

Here is my code.

import { injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/catch';

@Injectable({
    providedIn: 'root'
})
export class PostsService {
    private url = 'https://jsonplaceholder.typicode.com/posts';
    constructor(private http : Http ) { }
    getPosts {
        return this.http.get(this.url);
    } 

    deletePost(id) {
        return this.http.get(this.url + '/' + id);
    }
}

I am doing this code on my PC it's working but not working on a laptop. It seems funny but this is true.
This is the structure of my project

Kerch answered 11/5, 2018 at 11:40 Comment(6)
Did you do npm install to get all dependenciesLucho
May be an newer version of rxjs which no longer supports single imports. Try `import { catchError } from 'rxjs/operators;'Amero
Yes @ShashankVivek I tried using npm install as well as npm updateKerch
Module '"f:/Angular/angular-form/angular-form-app/node_modules/rxjs/Observable"' has no exported member 'Observable'. i am getting this error nowKerch
Angular CLI : 1.7.4 and Angular CLI : 6.0.1 What is the difference between this two ?Kerch
Try : import { Observable } from 'rxjs';Lucho
B
20

New version of rxjs no longer supports single imports, instead try:

import { catchError } from 'rxjs/operators';
Balkin answered 29/5, 2018 at 12:30 Comment(0)
M
18

In Angular 6 RXJS imports have been changed, operators must be "wrapped" in pipe() and written without a dot at the beginning (was: .map, .retry, .catch; now: map, retry and catchError instead of a catch):

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

and use pipe()

getPosts() {
    // pack in "pipe()"
    return this.http.get(this.url).pipe(
      // eg. "map" without a dot before
      map(data => {
        return data;
      }),
      // "catchError" instead "catch"
      catchError(error => {
        return Observable.throw('Something went wrong ;)');
      })
    );
  }

"I am doing this code on my PC it's working but not working on a laptop" - on the laptop you've a newer version of angular cli. It generates angular 6 with new, other imports. Regards

Mumbletypeg answered 19/9, 2018 at 15:17 Comment(1)
While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value.Grey
W
5

If you came here because of a Udemy Course which the initial code suggests.

imports

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

And this is how it should look now.

  deletePost(id){
    return this.http.delete(this.url + '/' + id ).pipe(
       catchError(error => {
         return throwError(() => new Error("..."));
      }));
  }
Wilkerson answered 30/6, 2020 at 19:38 Comment(0)
T
3

in angular 7, here is how to handle in a clean way the http get request

import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable, throwError} from 'rxjs';
import {catchError, retry} from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class EmployeeService {

  constructor(private _http: HttpClient) {
  }

  public getPosts(): Observable<Post[]> {

    return this._http.get(<URL>).pipe(
      retry(1), catchError(error => {
        return throwError(error.message);
      }));
  }
}
Trometer answered 16/12, 2018 at 8:51 Comment(0)
F
2

try this and will work!...

    import { Injectable } from '@angular/core';    
    import { HttpClient, HttpErrorResponse } from '@angular/common/http';    
    import { catchError } from 'rxjs/operators';    
    import { Observable, throwError } from 'rxjs';    


        .get(<URL>).pipe
         (
         catchError((error: HttpErrorResponse) =>{       
            return throwError(error.message || 'server error');    
                                                })
         )
Fatalism answered 6/1, 2019 at 9:0 Comment(0)
P
1

For recent versions of Angular (v13), the code is a bit different. Let's start with the service implementation:

import { NotFoundError } from './../common/not-found-error';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';
import { AppError } from '../common/app-error';
...
      deletePost(id: number) {
        return this.http.delete(this.url + '/' + id).pipe(
          catchError((error: Response) => {
            if (error.status === 404)
              return throwError(() => new NotFoundError(error));
            return throwError(() => new AppError(error));
          })
        );
      }

For a Separation of concerns purpose, the service is responsible for sending the delete request and catching any potential known (not found 404) or unknown error. In case of an error, the service throws an error by calling one of the application error classes (AppError which is a generic class and NotFoundError which is a specific error class and it extends AppError).

Note that the service delegates the error management to thoses 2 error application classes (the service role is not to go into error management details)

AppError (app-error.ts):

export class AppError {
  constructor(public originalError?: any) {}
}

NotFoundError (not-found-error.ts):

import { AppError } from './app-error';
export class NotFoundError extends AppError {}

Now for the posts.component.ts implementation, we should have something like:

import { NotFoundError } from './../common/not-found-error';
import { AppError } from './../common/app-error';
...
  deletePost(post: any) {
    this.service.deletePost(post.id).subscribe({
      next: () => {
        let index = this.posts.indexOf(post);
        this.posts.splice(index, 1);
      },
      error: (error: AppError) => {
        if (error instanceof NotFoundError)
          alert('this post has already been deleted');
        else {
          alert('An unexpected error occured.');
          console.log(error);
        }
      },
    });
  }

This deletePost method subscribes to the dedicated service, and in case the service catches and throws an error, deletePost will check the kind of the error and will show the error accordingly.

Pellagra answered 1/1, 2022 at 6:54 Comment(0)
K
-3

Why don't you try adding "import 'rxjs/add/operators/catch';" (put the 's' and make it operators) instead of "import 'rxjs/add/operator/catch';"

Kearse answered 29/5, 2018 at 5:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.