Error: Could not find module: Unable to locate 'rxjs/add/observable/throw' in 'D:\Angular\httpErrorHandlingExample\src\app'

I'm working on an Angular project to practice error handling, but I encountered an issue when trying to import the 'throw' module. The error message reads as follows: Error Message: "ERROR in ./src/app/employee.service.ts Module not found: Error: Can't resolve 'rxjs/add/observable/throw' in 'D:\Angular\httpErrorHandlingExample\src\app'" I'd appreciate any assistance with this problem.

employee.ts :

export interface IEmployee{
    id: number,
    name: string,
    age: number
}

employee.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { observable,Observable ,throwError} from 'rxjs';
import { IEmployee } from './employee';
//import 'rxjs/add/operator/catch';
import{ catchError } from 'rxjs/operators';
import 'rxjs/add/observable/throw';

@Injectable({
  providedIn: 'root'
})
export class EmployeeService {
  private _url: string ="/assets/data/employees1.json";

  constructor(private http: HttpClient) {}

    getEmployees(): Observable<IEmployee[]>{
      return this.http.get<IEmployee[]>(this._url)
                      .pipe(catchError(this.errorHandler));

   }

   errorHandler(error: HttpErrorResponse){
      return Observable.throw(error.message || "Server Error");

   }
}

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { EmployeeListComponent } from './employee-list/employee-list.component';
import { EmployeeDetailsComponent } from './employee-details/employee-details.component';
import { HttpClientModule } from '@angular/common/http';
import { EmployeeService } from './employee.service';

@NgModule({
  declarations: [
    AppComponent,
    EmployeeListComponent,
    EmployeeDetailsComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule
  ],
  providers: [EmployeeService],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'httpErrorHandlingExample';
}

app.component.html :

<app-employee-list></app-employee-list>
<app-employee-details></app-employee-details>

employee-list.component.ts

import { Component, OnInit } from '@angular/core';
import { EmployeeService } from '../employee.service';

@Component({
  selector: 'app-employee-list',
  template: `
  <h1>Service Example: Program NO.14</h1>
  <h2>Employee Details</h2> 
  {{errMgs}}
  <ul *ngFor="let emp of employees">
    <li>{{emp.name}}</li>
  </ul>
  `,
  styleUrls: ['./employee-list.component.css']
})
export class EmployeeListComponent implements OnInit {
  public employees;
  public errMgs;

  constructor(private _employeeservices: EmployeeService) { }

  ngOnInit() {
    this._employeeservices.getEmployees().subscribe(data =>this.employees=data,
                                                    error =>this.errMgs =error);
  }

}

employee-details.component.ts

import { Component, OnInit } from '@angular/core';
import { EmployeeService } from '../employee.service';

@Component({
  selector: 'app-employee-details',
  template: `
  <h2>Employee List detail</h2>
  <ul *ngFor="let emp of employees">
    <li>{{emp.id}}. {{emp.name}} {{emp.age}}</li>
  </ul>
  `,
  styleUrls: ['./employee-details.component.css']
})
export class EmployeeDetailsComponent implements OnInit {

  public employees=[];
  public errMgs;
  constructor(private _employeeservices: EmployeeService) { }

  ngOnInit() {

    this._employeeservices.getEmployees().subscribe(data =>this.employees =data,
                                                    error => this.errMgs =error);
  }

}

The employee details are store in the following folder locally:"/assets/data/employees.json"

Answer №1

The import statement you're using is incorrect:

import 'rxjs/add/observable/throw';

I believe the correct syntax should be:

import { throwError } from 'rxjs';


function errorHandler(error: HttpErrorResponse){
  return throwError(error.message || "Server Error");
}

}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Converting Blob to File in Electron: A step-by-step guide

Is there a way to convert a Blob into a File object in ElectronJS? I attempted the following: return new File([blob], fileName, {lastModified: new Date().getTime(), type: blob.type}); However, it appears that ElectronJs handles the File object differently ...

I can't figure out why I'm getting the error message "Uncaught ReferenceError: process is not defined

I have a react/typescript app and prior to updating vite, my code checked whether the environment was development or production with the following logic: function getEnvironment(): "production" | "development" { if (process.env.NODE_E ...

transmit URL parameters to Express using Angular 2

I have implemented an Angular service to retrieve data from Express: getRestaurants(districtId) : Observable<void[]>{ let params: URLSearchParams = new URLSearchParams(); params.set('id', districtId); return this.http.get(this.url, ...

Testing the Window beforeunload event method in an Angular unit test: A guide

Currently, I am actively involved in a project using Angular 8. One of the features I implemented was to show a confirm prompt when a user tries to navigate away from the site. This functionality was added by integrating the following function into my com ...

Attempting to integrate Bootstrap 5 accordion into Angular 17 using ngFor has posed a challenge for me

<div class="accordion w-50 mx-auto" id="accordionExample"> <div *ngFor="let note of notes; index as i;"> <div class="accordion-item"> <h2 class="accordion-header" id="headi ...

Adding an image to a React component in your project

I am currently working on an app that utilizes React and Typescript. To retrieve data, I am integrating a free API. My goal is to incorporate a default image for objects that lack images. Here is the project structure: https://i.stack.imgur.com/xfIYD.pn ...

Issues with Angular Structural Directives arising from NPM installation concerns are causing problems

I have developed an npm package called sezam-shareds To integrate the package into a new project, you need to follow these steps: Add the following component from the package: <sezam-overflow [show]="true"></sezam-overflow> to a compo ...

Specialized spinning tool not in sight

Having an angular 11 application with a spinner that should be visible during data loading from the backend. However, when the fa-icon is pressed by the user, it becomes invisible while waiting for the server response. The issue arises when the spinner its ...

Caution: Unable to load bindings, resorting to pure JS instead (consider running npm run rebuild?) within AWS SAM

When I run a sam local invoke to call a typescript AWS Lambda function locally, I am encountering a warning: 2023-04-04T08:53:29.931Z undefined WARN bigint: Failed to load bindings, pure JS will be used (try npm run rebuild?) Should I conf ...

The NullInjectorError is thrown when the Angular service providedIn: root is imported from a library

After moving my service into a separate npm package, I encountered an issue where the service was marked to be provided in the root injector but resulted in a NullInjectorError when trying to use it in my app. To solve this problem, I had to include Quer ...

What steps can be taken to retrieve error.data from RTK Query while utilizing typescript?

When I log error to the console, this is what I see: { status: 401, data: "Invalid password" } If I attempt to log error.data, an error occurs: The "data" property does not exist in the "FetchBaseQueryError|SerializedErr ...

Deactivate the button while the form is being submitted

I need a way to prevent users from clicking the submit button multiple times while the form is being processed by the server. Below is the solution I have come up with: clear() { this.count++ this.formGroup.get('name').reset(null); ...

Is your CSS looking chaotic on both the login and dashboard pages?

I am facing a major issue with my CSS not cooperating properly with my Angular project. When I attempt to log in on the login page username = toto password = 123 I have set up a demo here. https://i.sstatic.net/NBeWA.png I expect to see this view htt ...

Combining data from various API calls into one cohesive array using RXJS

My RXJS Pipeline is structured as follows: const logs: number[] = [1, 2, 3, 4]; const url = 'http://some-url-here.com'; const pipeline = from(logs).pipe( switchMap(logId => this.callEndpoint(url, logId).pipe(map(response => response. ...

The recursive component is functional exclusively outside of its own scope

I'm facing an issue where my recursive component is not nesting itself properly. The problem arises when I try to use the Recursive component inside another Recursive component. Although the root is correctly inserted into the Recursive component fro ...

Challenges with E-commerce Project's Wishlist Feature

Currently, I am working on a project where clicking on the 'fa-heart' icon should toggle between solid and regular states to add or remove an item from the wishlist. However, my attempts so far have resulted in all product icons changing together ...

Webpack is throwing an error due to the Vue component type being labeled as "any"

When using ts 4.2.4 and Vue3, I encountered a strange error while building my vue project: > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c3a2a7aeaaededb3a2a0a083f3edf2edf3">[email protected]</a> build > v ...

Experiencing issues during the execution of "ng serve"

The angular project is named "PaymentApp". When running "ng serve", numerous errors are displayed instead of the default angular template. The message "Cannot GET /" is being shown. Attached images for reference: https://i.stack.imgur.com/faysG.png http ...

Unable to identify the versions of "@angular/cli" as the local installation seems to be faulty

My local installation broke after installing the Momento plugin. This plugin caused issues. When I try running my project with the command ng serve, I get this error message: Cannot determine versions of "@angular/cli". This likely means your local ...

What is the correct way to close an ngx-contextmenu in an Angular application?

In my angular project, I implemented an ngx-contextmenu. Within one of my components, the template includes the following code: <div... [contextMenu]="basicMenu"> <context-menu>..... </div> After some time, the component with the conte ...