Guide on retrieving the response value from the httpclient in Angular 6

I am utilizing HttpClient for sending requests. I have created a service to handle this.

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

@Injectable({
  providedIn: 'root'
})
export class HttpService {
  apiRoot: string = 'https://xxxx/api';

  constructor(private http: HttpClient) { }

  getQueryParam(obj) {
    let search = new HttpParams();
    for (let key in obj) {
      search =  search.set(key, obj[key]);
    }
    return search;
  }


  post(apiURL, params, data){
    console.log('Inside Post Request');
    let paramsData = this.getQueryParam(params);
      let CompleteURL = `${this.apiRoot}` + apiURL;
      return this.http.post(CompleteURL,data,{params : paramsData,observe : 'events'});
  }
}

In my component:

login() {
    this.admin.password = Md5.hashStr(<string>this.admin.password);
    this._httpService.post('/loginAdmin', { "name": "vinay" }, this.admin)
      .subscribe(res => {
        console.log(res.success);

      },
        (err: HttpErrorResponse) => {
          if (err.error instanceof Error) {
            console.error('An error occurred:', err.error.message);
          } else {
            console.error(`Backend returned code ${err.status}, body was: ${err.error}`);
          }
        }
      );
  }

When trying to access the response body value in my component, an error is shown stating that "Property 'success' does not exist on type 'HttpEvent<Object>'". I have researched online and found suggestions about creating an interface, but the issue persists as "res.success" can be either an array or object. Any assistance would be greatly appreciated.

Answer №1

secureLogin() {
    this.user.password = Md5.hashStr(<string>this.user.password);
    this._httpService.post('/authenticateUser', { "username": "johndoe" }, this.user)
      .subscribe((response: any) => {
        console.log(response.message);

  },
    (error: HttpErrorResponse) => {
      if (error.error instanceof Error) {
        console.error('An unexpected error occurred:', error.error.message);
      } else {
        console.error(`Server returned status code ${error.status}, response body: ${error.error}`);
      }
    }
  );
}

When handling the response from the service, make sure to use any as the type. Hopefully, this will be useful for you :)

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

Troubleshooting issue with Material UI icons in React application with Typescript

I created a set of icons based on a github help page like this: const tableIcons = { Add: forwardRef((props, ref) => <AddBox {...props} ref={ref} />), DetailPanel: forwardRef((props, ref) => ( <ChevronRight {...props} ref={ref} /> ...

The async validator in Angular will only activate upon submission if the user has made changes to the form

In my angular 10 application, I have implemented a login form with various validation checks for the username and password fields. These validations are carried out using an async validator that is applied to the formgroup containing the username and pass ...

Implementing the ternary operator on a nested object field in typescript to enforce type validation

Is there an issue with my code or is this intentional? I want to write something similar to this. type MyDefinition = { salutation: string; value?: { typeOfValue: string; val?: string }; }; function create(name: string, input?: Partial<MyDefin ...

What are the steps for utilizing CzmlDataSource within React Resium?

Currently, I'm attempting to showcase the data from a local czml file on a map using React, Typescript, and Resium. Unfortunately, an error keeps popping up stating "This object was destroyed, i.e., destroy() was called." Can someone point out where m ...

What is the best method for typing a component prop that is compatible with singular use and can also function within loops without disrupting intellisense?

The Scenario Within a heading component, I have defined various types as shown below: // Heading/index.d.ts import { HTMLAttributes } from 'react'; export const HeadingType: { product: 'product'; marketing: 'marketing'; ...

Multiple subscriptions without having to recalculate the shared components

const ex = ajax.getJSON('https://httpbin.org/get?a=24'); ex.pipe(pluck('args')).subscribe(x => console.log('Arguments: ', x)); ex.pipe(pluck('headers')).subscribe(x => console.log('Response Headers: ' ...

Is There a Comparable Feature to *ngIf in DevExtreme?

Currently, I am diving into the world of webapp development using DevExtreme. As a novice in coding, this is my first time exploring the functionalities of DevExtreme. Essentially, I am seeking guidance on how to display certain elements based on specific ...

issue with angular and typescript

I'm currently working on developing an Angular 2 application that incorporates touch gestures using hammerjs. My goal is to merge the quickstarter application from: Angular 2 with the hammerjs application from: Hammerjs sample. However, I keep encou ...

Challenge your TypeScript skills: convert snake_case to camelCase and back again

I am looking to develop a Typescript function that can deeply traverse a plain object and convert all snake_case keys to camelCase. Additionally, I need a function that can convert camelCase keys to snake_case throughout the object. While implementing thi ...

Angular routing typically directs users to the home page

I've been struggling for hours trying to solve what seems like a simple issue. I have a route called page2 set up in the following way: // app.module.ts import { Page2Component } from './page2/page2.component'; @NgModule({ declarations: ...

What causes the inconsistency in the form input value when it is disabled?

I have encountered an issue while working on an Angular input component in StorybookJS. The problem arises when I enter a value (e.g., hello) in the Control Panel in Storybook JS and set disabled to true. The input text becomes disabled and displays the te ...

Issue with Date generation in TypeScript class causing incorrect date output

I have a simple code snippet where I am creating a new Date object: var currentDate = new Date(); After running this code, the output value is: Sat May 11 2019 13:52:10 GMT-0400 (Eastern Daylight Time) {} ...

Vue + TypeScript prop type issue: "'Foo' is intended as a type, but is being treated as a value in this context."

As a newcomer to TypeScript and the Vue Composition API, I encountered an error that left me puzzled: I have a component that requires an api variable as a prop, which should be of type AxiosInstance: export default defineComponent({ props: { api: A ...

Angular 2 mistakenly utilizing incorrect RouterOutlet

I'm facing an issue with implementing md-tabs along with the router-outlet to avoid preloading all data at once. My goal is to load data only when needed. AdminComponent.html <a [routerLink]="['categories']"><h1>to categories&l ...

The Angular 13 application encounters a "moment is not a function" error after importing an Angular 13 package

Upgrading a private library named privLib to Angular 13 has been my recent task in order to facilitate the migration of all other projects. However, an issue arises when this library is imported into another project where one of the services utilizes momen ...

Assign the chosen option in the Angular 2 dropdown menu to a specific value

Currently, I am utilizing FormBuilder in order to input values into a database. this.formUser = this._form.group({ "firstName": new FormControl('', [Validators.required]), "lastName": new FormControl('', [Validators.required]), ...

creating a fresh instance of a class while in a subscribe method

Although this code is functional, it briefly displays incorrect data because a blank token is instantiated before being populated in the subscribe function. Is there a way to move the instantiation into the subscribe function or provide all necessary par ...

TypeScript Error: The Object prototype must be an Object or null, it cannot be undefined

Just recently, I delved into TypeScript and attempted to convert a JavaScript code to TypeScript while incorporating more object-oriented features. However, I encountered an issue when trying to execute it with cmd using the ns-node command. private usern ...

NG instruction failing to execute

I've tried every ng command possible, but nothing seems to be working for me. https://i.sstatic.net/BIeSq.jpg Even after installing the latest angular/cli and confirming that it's in my environment variables PATH C:\Users\david\ ...

How can Angular2 detect when an entity is clicked within a window?

There are multiple items generated using *ngFor: <my-item *ngFor="let item of myArray" [p]="item"></my-item> I am able to handle a click event like this: <my-item ... (click)="doWork(item)"></my-item> However, I want to avoid a ...