Angular7 is throwing an error saying it cannot read the property 'post' of undefined

Looking to create a custom validation in Angular 7.

Here is the code snippet:

CheckUserNameExisit(control: AbstractControl): { [key: string]: any } {
 console.log('in functions')
 return new Promise(resolve => {
  let httpClient: HttpClient;
  var userService = new UserService(httpClient);
  let usernameExist: Usernameexist;
  usernameExist = userService.InitialUserNameExist();
  usernameExist.UserName = control.value;
  console.log(usernameExist.UserName)
  userService.checkUsername(usernameExist)
    .subscribe(data => {
      if (data.success == false) {
        console.log(data.success)
        resolve({ 'usernameExists': false });
      } else {
        console.log(true)
        resolve(null);
      }
    });
});
}

and this is UserSerivce :

checkUsername(item: Usernameexist): Observable<GenericModel<Usermodel>> {
  console.log('go')
  return this.httpClient.post<GenericModel<Usermodel>>('https://localhost:44372/api/v1/User/FindbyName/', item);
}

However, when attempting to use this validation, an error occurs:

ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'post' of undefined TypeError: Cannot read property 'post' of undefined at UserService.push../src/app/services/user.service.ts.UserService.checkUsername

What could be causing this issue? How can it be resolved?

Answer №1

When working with the userservice module, remember to include Httpclient

import { HttpClient } from '@angular/common/http';

constructor(private http: HttpClient) { }

Answer №2

It appears that the `HTTPClientModule` is missing from your code. According to Angular documentation:

In your app.module.ts file:

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

@NgModule({
  imports: [
    BrowserModule,
    // Ensure you import HttpClientModule after BrowserModule.
    HttpClientModule,
  ],
  declarations: [
    AppComponent,
  ],
  bootstrap: [ AppComponent ]
})
export class AppModule {}

And in your service.ts file:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class YourService {
  constructor(private http: HttpClient) { }
}

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

The functionality of the vue2-timepicker package seems to be malfunctioning in vue.js

I am utilizing the vue2-timepicker JavaScript package. npm install vue2-timepicker --save Following that, I import the CSS and datetimepicker component file from node_modules into my main.js file // import the CSS file import 'vue2-timepicker/dist ...

Unable to execute xmlHttp.responseXML on a server that is offline

Currently, I am diving into the world of AJAX and XML. However, I recently encountered a frustrating issue. I attempted to create a basic program that would display everything I input into an input box within a <div>. Strangely enough, my program fa ...

My pathways are clearly mapped out, yet express is returning a frustrating 404 error

After exhausting all the similar posts on StackOverflow without finding a solution... Let's take a look at my app.js, which is the first file that the express library seeks when launching the app right after my server.js file responsible for setting ...

The build process encountered an error while processing the module vue-router.esm.js in a Vue.js

Just started using VueJs and decided to incorporate the cli-plugin-unit-jest into my project. However, after adding it, I encountered the following error: Failed to compile. ./node_modules/vue-router/dist/vue-router.esm.js Module build failed: Error: ENO ...

What is the process for building an Angular project using JSON files so that the values can be easily updated post-build to display various outcomes?

Is there any other way to build without using ng build? I'm encountering an issue where the build JSON values are embedded in main.js, preventing me from easily changing them later. I need to generate a report in HTML format with a JSON file using Ang ...

Transfer the value of a variable within the local scope to the dragstart event handler during the dynamic generation of an input element

After going through several similar questions, I couldn't find a solution that applies to my specific case. Here is the loop I am working with: $.each(data.modules, function(i, field) { let $li = $(`<li><div> Name: ${field.name}</div& ...

Looking for a way to add interactivity to this canvas rectangle?

ctx.fillStyle = "#9b958c"; ctx.fillRect(sampleRectX, sampleRectY, sampleRectW, sampleRectH); ctx.fillStyle = "#fff"; ctx.fillText("Click here to play again.", sampleTextX, sampleTextY); This clickable rectangle has been giving me some trouble. While I fou ...

What is the best way to utilize AJAX for retrieving numerous data sets from a PHP file?

Currently, I am tackling a project that involves an HTML file containing two different divs: one for "product" and the other for "price". These divs need to display text from rows in a database, which can be accessed easily using a PHP file. Using AJAX, I ...

Adjust ion-select label width across the entire screen in Ionic version 6

I recently began working on a fresh project using Ionic v6. As part of the development, I included a basic ion-select element in my HTML code: <ion-item> <ion-select placeholder="Select Option"> <ion-select-opti ...

Calling this.$refs.upload.submit() is not providing the expected response from Element-UI

Currently working with element-ui and attempting to upload a file using the following code: this.$refs.upload.submit(); Is there a way to retrieve the response from this.$refs.upload.submit();? I have attempted the following: .then(response => { t ...

Using AngularJS to Showcase JSON Array

I am currently working with a .json file that contains information about networks, IP addresses, and zones. I am trying to figure out how to display the "ip" array in my .html file. [ { "network":"net1", "ip":[ "19 ...

Customize Bottom Navigation Bar in React Navigation based on User Roles

Is it possible to dynamically hide an item in the react-navigation bottom navigation bar based on a specific condition? For example, if this.state.show == true This is what I've attempted so far: const Main = createBottomTabNavigator( { Home: { ...

Adjust the height of an element using CSS based on the height of another

Is there a way to have two divs per row, where the second div always displays its full content and the height of the first div matches the height of the second div? If the content in the first div exceeds the height, it should be scrollable. I've atte ...

The Formik form is not being populated with data from the API

While working on a functional component in ReactJS, I created a simple form using Formik. The input fields in my form are supposed to fetch data from an API when the component mounts. To achieve this, I utilized fetch and useEffect. However, after fetching ...

Angular view not reflecting changes made to the model

Here is a straightforward Angular application I created to play audio using the JavaScript web Audio Object: app.component.ts export class AppComponent { title = 'media player'; audio; currentTime: number; constructor() { this.audi ...

When subscribing to ActivatedRoute, the params object contains various attributes to store the passed parameter values

When subscribing to params in targetComponent: import { ActivatedRoute } from '@angular/router'; export class TargetComponent { constructor(private activeRoute: ActivatedRoute) { this.activeRoute.params.subscribe(params => { ...

What sets apart using the loadText function from loadText() in JavaScript?

I've implemented a basic JS function that loads text lines into an unordered list. Javascript function loadText() { document.getElementById("text1").innerHTML = "Line 1"; document.getElementById("text2").innerHTML = "Line 2"; document.ge ...

Is there a way to display the HTML input date by simply clicking on text or an image?

I need to display a date picker when I click on specific text or an image. I am working with reactjs and utilizing the HTML input type="date", rather than the React-datepicker library. Here is the code snippet: import { useRef } from "r ...

What is the best method for starting a string using the symbol '~'?

Hello everyone! I have a task that requires me to add a special feature. The user needs to enter something in a field, and if it starts with the tilde (~), all subsequent entries should be enclosed in a frame within the same field or displayed in a list ...

Simply tap on the image to include it in the HTML5 Canvas drawing

Currently, I am in the process of drawing a circle onto my html5 canvas as shown in the code snippet below: <!DOCTYPE HTML> <html> <head> <style> body { margin: 0px; padding: 0px; } </style> </head> <body> &l ...