What could be causing the Angular error related to this HttpHeader?

Is there anyone who can assist me with why I am encountering an error in my Angular code while trying to use HttpHeaders to read the response status from the backend? Here is the specific error message: https://i.sstatic.net/tQu5t.jpg

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { map } from 'rxjs/operators';

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

  // Base API URL
  public url = 'http://localhost:8080/';
  headerProperty: string;

  constructor(private http: HttpClient) { }

  createUser(data) {
    return this.http.post(this.url + 'todo', data);
  }

  createAddress(data) {
    return this.http.post(this.url + 'address', data);
  }

  loginStudent(data) {
    const postHttpOptions = {
      headers: new HttpHeaders({
      'Content-Type':  'application/json'
   }),
  observe: 'response' as 'body'
 };

  return this.http.post('http://localhost:8080/' + 'login', data, 
postHttpOptions)
  .pipe(map(response => {
         return response;
    }));

  }
}

I have made modifications to the code by adding 'as body' into it, but now a new issue has arisen with my component.

saveStudentDetails(values) {
  const studentData = new FormData();

  studentData.append('id', values.id);
  studentData.append('password', values.password);
  this.crudService.loginStudent(studentData).subscribe(result => {
    if (result.headers.status === '202') {
      this.router.navigate(['address']);
      alert('"success"');
      return;
    }
  });
}

The error states that the property 'headers' does not exist on type 'object'.

Answer №1

The reason for the error is that result is of type {}, which does not have any properties. To resolve this, you can specify a type by doing one of the following:

this.http.post<any>(...)

Alternatively,

(result: any)

However, using any is considered bad practice in TypeScript. It's better to define your response structure in a custom interface as shown below:

export interface ICustomResponse {
  data: any;
  error: string;
}

Then, you can use it like this:

this.http.post<ICustomResponse>(...)

Or,

(result: ICustomResponse)

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

Resolving Node.js Troubles: An Encounter with 'Module Not Found' Error

After generating a new application, I encountered an error while using the "ionic serve" command. [ng] The specified path cannot be found. [ng] internal/modules/cjs/loader.js:883 [ng] throw err; [ng] ^ [ng] Error: 'C:\Users\shane\Co ...

Tips for obtaining a variable step size in react-chartjs-2

I am currently utilizing Chart.js in typescript to create graphical charts. My objective is to dynamically adjust weight values while maintaining a specified minimum and maximum. Specifically, I aim to display 5 ticks on the Y-axis regardless of the incomi ...

Exploring the Wonders of Hot Chocolate Graphql Integration with Angular Apollo Code Generation

Exploring the functionality of the Apollo GraphQL codegen for Angular is my current endeavor. To achieve this, I have set up a .NET 5 server hosting a GraphQL endpoint at https://localhost:8081/api/graphql/. The server is up and running smoothly without ...

Struggling to explore all the features of the Year selection in the Angular ng Bootstrap datepicker?

Currently, I am utilizing Angular 8 in conjunction with ng Bootstrap Datepicker. The issue I am encountering is that the year range within the DatePicker dropdown for selecting a year is limited. Below is the code snippet I am using: <div class="form ...

Refine current attributes of an object in Typescript

In typescript, I have an object of type any that needs to be reshaped to align with a specific interface. I am looking for a solution to create a new object that removes any properties not defined in the interface and adds any missing properties. An exam ...

Angular Input Validation for Multiple Entries

Has anyone else tried creating a validator that checks for duplicate email addresses in a list? I am attempting to implement this feature where the validator takes an email address from a text input and compares it against a list of emails. The code snipp ...

Searching for nicknames in a worldwide Jest arrangement?

Before running all test cases, I need to execute certain tasks only once. To achieve this, I have created a global function and specified the globalSetup field in my Jest configuration: globalSetup: path.resolve(srcPath, 'TestUtils', 'global ...

Electron does not have the capability to utilize Google's Speech to Text engine

I am trying to connect my microphone with the Google Speech to Text engine. I came across this page and copied the code into my renderer.ts file, uncommented the lines with const, but when I run it, I encounter an error at line 7 (const client = new speech ...

"Uh-oh! Debug Failure: The statement is incorrect - there was a problem generating the output" encountered while attempting to Import a Custom Declarations File in an Angular

I am struggling with incorporating an old JavaScript file into my Angular service. Despite creating a declaration file named oldstuff.d.ts, I am unable to successfully include the necessary code. The import statement in my Angular service seems to be worki ...

Nextjs REACT integration for self-service registration through OKTA

Attempting to integrate the Okta SSR feature for user sign-up in my app has been challenging as I keep encountering this error message: {"errorCode":"E0000060","errorSummary":"Unsupported operation.","errorLink& ...

Adding a .pdf file to the src folder in Typescript React: A simple guide

I've been working on enhancing my portfolio site by adding my resume in .pdf format for easy download when a button is clicked. To do this, I placed my .pdf file along with a "types.s.ts" folder in the src directory. In order to implement this, I imp ...

Manage two distinct approaches for two separate phone calls

We have a situation where two components are involved. In the first component, there is a repeated call to a specific page (select-person/{{person.id}}) component1.html : <td><a routerLink="select-person/{{person.id}}" class="person_ ...

Angular 8 Observable: Managing User Objects

I recently developed a new service and attempted to call an API method (HTTP GET) to retrieve data, but I'm encountering an issue where not all the data objects from the API GET request are being displayed. angular-component.ts public allUsers$: Obs ...

Ways to extract information from the asObservable() method

This is my service code, and I've named the service setGetContext. _params: Subject<any> = new Subject<any>(); getParameters(): Observable<SearchContext> { return this._params.asObservable(); } setParameters(search: SearchCont ...

Issue: "Stumbled upon an unknown provider! This often implies the presence of circular dependencies"

Looking for help on a perplexing error in my Angular / TypeScript app. While we wait for an improved error message, what steps can we take to address this issue? What are the potential triggers for this error to occur? Uncaught Error: Encountered undefi ...

How to vertically align Material UI ListItemSecondaryAction in a ListItem

I encountered an issue with @material-ui/core while trying to create a ListItem with Action. I am looking for a way to ensure that the ListItemSecondaryAction stays on top like ListItemAvatar when the secondary text becomes longer. Is there any solution to ...

When using ng g module my-module command, it will only create the module.ts file without

When running the command ng g module my-module, only the module.ts file is generated. However, I require all the additional files such as css, HTML, ts, spec, and module.ts. Is there a way to generate all of these at once using the CLI? ...

Differences between Angular 4 and AngularJs directives

Delving into the world of Angular 4, I have encountered a slight hurdle in my understanding of directives. My goal is to create a directive that can resize an element based on its width. Back in the days of AngularJs, this task was accomplished with code r ...

Dealing with GraphQL mutation errors without relying on the Apollo onError() function

When managing access to an API call server-side, I am throwing a 403 Forbidden error. While trying to catch the GraphQL error for a mutation, I experimented with various methods. (Method #1 successfully catches errors for useQuery()) const [m, { error }] ...

Exploring the node_modules directory within Angular 2

In my Angular 2 App, I am facing an issue with the folder structure. When I try to import 'MultiselectDropdownModule' on line 23, I receive an error stating "Not found". How can I properly map the node_modules folder and avoid using absolute path ...