Angular 5: experiencing issues with HttpClient when using REST API

Currently, I am in the process of developing a REST API using Spring to perform CRUD operations based on a tutorial I found. However, I have encountered an issue with the HTTP client not retrieving data, and upon inspection, I discovered the following error:

GET sockjs.js:1606 GET http://localhost:9000/sockjs-node/info?t=1626851020608 net::ERR_CONNECTION_REFUSED

I can confirm that my server is up and running, and the URL is accurate. I have also included Access-Control-Allow-Origin origin in the header. Removing this results in another error related to CORS policy denial.

Below is the code snippet from my employee.service.ts file:

import { Injectable } from '@angular/core';
import { HttpClient} from '@angular/common/http' ;
import { Observable } from 'rxjs';
import { Employee } from './employee';

@Injectable({
  providedIn: 'root'
})
export class EmployeeService {
 
   private baseUrl = "http://localhost:8080/api/v1/employees" ;
   constructor(private httpClient: HttpClient) { }

   getEmployeesList() : Observable<Employee[]>
   {
     return this.httpClient.get<Employee[]>(`${this.baseUrl}`) ; 
   }
}

And here is the content from my employee-list.component.ts file:

import { Component, OnInit } from '@angular/core';
import { Employee } from '../employee' ;
import { EmployeeService } from '../employee.service';
@Component({
  selector: 'app-employee-list',
  templateUrl: './employee-list.component.html',
  styleUrls: ['./employee-list.component.css']
})

export class EmployeeListComponent implements OnInit {

  employees!: Employee[]; 
 
  constructor(private employeeService : EmployeeService) { }

  ngOnInit(): void {
      this.getEmployees();
  }
  private getEmployees()
  {
    this.employeeService.getEmployeesList().subscribe(data => this.employees);
  }

}

Lastly, the controller implemented in Spring Boot can be seen below:

package net.javaguides.springboot.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import net.javaguides.springboot.repository.EmployeeRepository ;
import net.javaguides.springboot.model.Employee ;

@CrossOrigin("*") 
@RestController
@RequestMapping("/api/v1/")
public class EmployeeController {
    
    @Autowired
    private EmployeeRepository  employeeRepository ;
    
    //get all employees
    @GetMapping("/employees")
    public List<Employee> getAllEmployees()
    {
        return employeeRepository.findAll() ;
    }

}

Despite multiple attempts, I continue to face issues with the GET request being denied consistently.

Answer №1

This issue is unrelated to the initial request you made.

sockjs.js:1606 GET http://localhost:9000/sockjs-node/info?t=1626851020608 net::ERR_CONNECTION_REFUSED

The line

subscribe(data => this.employees)
does not properly assign the value of data to the property this.employees. To correct this, the following code should be implemented:

  ngOnInit(): void {
      this.fetchEmployees();
  }
  private fetchEmployees()
  {
    this.employeeService.getEmployeesList().subscribe(data => this.employees = data);
  }

I opted to change from getEmployees to fetchEmployees as it follows a convention where the prefix get is used when there is an expected return value from the function execution. In this scenario, nothing is being returned.

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

Require type parameter to be of enum type

I have a specific goal in mind: // first.ts export enum First { One, Two, Three } // second.ts export enum Second { One, Two, Three } // factory.ts // For those unfamiliar, Record represents an object with key value pairs type NotWorkingType ...

Update the MySQL database conditionally depending on whether a column value has reached a specific final state, such as -1

Imagine having a table with three columns - ID, Name, and Status. The Status column can have values of -1, 0, 1, or 2. Initially, the default value is always 0, but upon update, it can change to 1, 2, or -1. Is there a way to enforce a constraint where onc ...

Using Material UI date picker with TypeScript: A Complete Guide

Well, I have to admit that I usually don't resort to putting 'any' as the type when I'm uncertain what to do, but right now, I'm starting to feel quite frustrated. I'm currently working with Material UI date picker in conjunct ...

The argument labeled as 'Subscription' cannot be assigned to the parameter labeled as 'string' in Angular

I am utilizing my Subscription variables to retrieve the API from configuration settings. public ChannelsAPI=this._configservice.getConfiguration("ChannelAPI").subscribe((result) => console.log(result)); This is the method _Configservice.getC ...

RxJs Subject: Acquiring the Sender

I have been working with Subjects and there is a .subscribe() in a specific class. Emitting values to this class from different other classes has resulted in the subscribe function being triggered multiple times, yet I am unsure of where these emits are co ...

The latest update for angular-devkit/build-angular (version 0.13.4) has brought a new issue with the configuration output. It seems that there is an unrecognized property

After upgrading a project from angular-devkit/build-angular v0.11.4 to v0.13.4, an error is now appearing: Invalid configuration object. Webpack has been initialised using a setup that does not align with the API schema. - configuration.output contains a ...

Disabling ngIf but still utilizing ngContent will render the template bindings

Creating a basic component in the following way: @Component({ selector: 'loader', template: `<div *ngIf='false'> <ng-content></ng-content> </div>`, }) export class Loader {} When it is imple ...

Receiving a reply from the axios function

Whenever I try to call the lookUpItem function from ItemSearch.vue, I always get an undefined response. Code snippet from ItemSearch.vue: <script setup lang="ts"> import { lookUpItem } from '../systemApi' async fu ...

Encountering a problem with the 'string' parameter when using TypeScript

I keep encountering the following error message: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ barkingRoadProject: string[]; }'. No index signature with a paramet ...

Streamlined Authorization in MEAN (SPA) Applications

I have created an application, but now I am trying to adapt it into a SPA application. The main issue I am facing is with the Authorization process. While I can successfully register new users, log them in, and retrieve their tokens, I seem to encounter a ...

What could be the root cause behind the error encountered while trying to authenticate a JWT?

I've been working on integrating a Google OAuth login feature. Once the user successfully logs in with their Google account, a JWT token is sent to this endpoint on my Express server, where it is then decoded using jsonwebtoken: app.post('/login/ ...

By constantly subscribing to a Behavior Subject, updating the data, and then resetting the value, an endless loop is created

We have implemented a wizard functionality with lazy loading, consisting of a parent component and multiple child components. const routes: Routes = [ { path : '', component : WizardHomeComponent, canActivate: [HomeGuard], chil ...

I'm having trouble getting the [resetFilterOnHide]="true" functionality to work with primeng 5.2.7. Can anyone provide a solution for this issue?

I'm experiencing an issue with the p-dropdown component where the [resetFilterOnHide]="true" attribute isn't working as expected. When I type in the filter bar, close the dropdown by clicking outside of it, and then reopen it, the entered filter ...

Converting JSX files to TSX files: a step-by-step guide

I am facing an issue with this particular component on the website. It is currently in .jsx format while the rest of the website uses .tsx files. I need to convert this specific component into a .tsx file. Can someone provide assistance or guidance? Despit ...

Is it still relevant to use the href attribute in Angular development?

Is there any specific benefit to either including or excluding the href attribute on internal links within an Angular 7 single-page application? Regardless, the functionality remains intact as Angular primarily relies on the routerLink attribute. ...

Every time I make updates, I have to reload the page to see the changes take effect

Currently, I am in the process of developing a web application that utilizes Firebase Firestore as the backend and NoSQL database, with Angular serving as the frontend. With frequent updates and changes being made to the website, it becomes cumbersome to c ...

Button for enabling and disabling functionality, Delete list in Angular 2

I am looking to toggle between the active and inactive classes on a button element. For example, in this demo, there are 5 buttons and when I click on the first button it removes the last one. How can I remove the clicked button? And how do I implement the ...

Building basic objects in TypeScript

My current project involves utilizing an interface for vehicles. export interface Vehicle { IdNumber: number; isNew: boolean; contact: { firstName: string; lastName: string; cellPhoneNumber: number; ...

Incorporate Node Red seamlessly into your current Angular application

We're excited to integrate Node Red as a low-code platform for building workflows within our application. To make this happen, we need the Node-Red editor to seamlessly run within our app so that our users can easily create their own workflows. I&apo ...

When the button is clicked, (ngSubmit) will be triggered

In my Angular2 Form Component, I have implemented two buttons with different functionalities. Button Submit: This button submits all the values to the API. Button Add: This button adds an object to an array. Here are the two methods: onSubmit() { this. ...