Struggling to make HttpClient Post work in Angular 5?

I'm facing an issue with my httpClient post request. The service is not throwing any errors, but it's also not successfully posting the data to the database.

Below is the code snippet:

dataService.ts

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

const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};

@Injectable()
export class DataService {

  constructor(private http: HttpClient) {}

  insertData() {
    const body = JSON.stringify({firstName: 'Joele', lastName: 'Smith4'});
    return this.http.post('http://myurl/index.php', body, httpOptions);
  }

}

app.component.ts

import { Component } from '@angular/core';
import { DataService } from './services/data.service';

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

  constructor(private dataService: DataService) {}

  myInsert() {
    if (this.dataService.insertData()) {
      alert('Data Inserted Successfully');
    }

  }

}

Lastly, here's app.component.html

<div (click)="myInsert()">Click Me</div>

I've analyzed the network tab in Chrome, but no POST requests are visible. How can I address this issue?

Answer №1

Observing observables is important in order to initiate a request.

insertNewData() {
  this.databaseService.addData().subscribe(
    response => console.log(response),
    error => console.log(error)
  );
}

Answer №2

I encountered a similar issue and found success by utilizing FormData in the following manner. Give it a try, it worked for me.

submitData() {
    let formData = new FormData();
    formData.append('firstName', 'Joele');
    formData.append('lastName', 'Smith4');

    return this.http.post('http://myurl/index.php', formData, httpOptions);
}

Answer №3

const userDetails = new FormData();
userDetails.append('firstName', 'Joele');
userDetails.append('lastName', 'Smith4');

this.http.sendFormData('http://myurl/index.php', userDetails, httpOptions);

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

Using Angular 2 to Create Nested ngFor Loops

I'm facing an issue that I can't seem to resolve. I attempted to use *ngFor in my code, but it seems that I am making a mistake with nested ngFor loops. To illustrate what I need to achieve, I ended up writing some messy code just to show the str ...

Angular's queryParams do not appear to properly connect with the query parameters

My code seems to have a mistake somewhere, but I can't figure it out. In my [queryParams] = "{allowEdit: server.id == 3 ? 1 : 0}", the params object is empty when I subscribe to it in the edit-server component. Why is it empty and how do I a ...

typescript warns that an object may be potentially null

interface IRoleAddProps { roles: Array<IRole> } interface IRoleAddState { current: IRole | null } class RoleAdd extends React.Component<IRoleAddProps, IRoleAddState> { state = { current: null, } renderNoneSelect = () ...

Generating a UTC timestamp in TypeScript

I am currently facing an issue with my application where I need to ensure that it always uses UTC time, regardless of the system time. I have a method in place to create a date: public static createDate(date: Date = new Date()): Date { return new Dat ...

What is the best way to extract information from an observable stream?

Within my codebase, there exists an observable that I have defined as: public selectedObjectsIds$ = of(); In addition, there is another stream present: this.reportMode$.pipe( filter((state: ReportMode) => state === ReportMode.close) ) .subscribe(() ...

Enhancing the 'UserDetails' model in ASP.NET Angular project (dotnet core 3.0) to accommodate additional user information

Currently working on an ASP.NET Web application with Angular as the front end, using the new template in VisualStudio 2019 for ASP.NET angular with Individual Authentication. This project runs on dotnet core 3.0 Preview 4. https://i.stack.imgur.com/RUKdg. ...

What is the purpose of the 'unique' keyword in TypeScript?

While coding in the TypeScript playground, I stumbled upon a situation where the term unique seems to be reserved. However, I haven't been able to find any official documentation regarding this. https://i.stack.imgur.com/eQq5b.png Does anyone know i ...

Tips for submitting a request following a change in the variable

I am in the process of developing a React application and I have implemented Auth0 for authentication. My goal is to initiate an HTTP request upon page refresh, but only if the variable isLoading is false. This way, I can access the user object once the ...

Encountered a Build Error in Visual Studio 2019 while working on an Angular Application

Recently, I created an application using Angular 8 and .Net Core 2.2 (Web API) in Visual Studio 2019 (Community Edition). To streamline the project organization, I followed the guidelines provided in this informative link: Add angular 7.0 client applicatio ...

My initial venture into Solidity DApp development, Encounter of an Unresolved Runtime

As I embark on developing my inaugural Solidity DApp using Next.js and Hardhat, I've encountered a perplexing error. After successfully deploying my contract on a local blockchain via npx hardhat node, the issue arises when calling the getProposalCoun ...

Is Angular equipped with named routes or states similar to UIRouter?

When working with AngularJS and ui-router, we define a state like this: .state('myState', { url: 'some-user-friendly-url' ... }) This allows us to easily specify the URL and name of the state. It simplifies navigation by letting ...

Turn off TypeScript's type validation during production builds

For my petite project, I am utilizing Next.js with TypeScript. A thought has been lingering in my mind lately: is there a way to turn off the types validity checks while executing npm run build? Since the type checking occurs during npm run dev, it seems ...

The function is not properly defined for the provided service

I am facing an issue with a service that is provided in app.module.ts and injected into an exported function within the same module. Despite this setup, when running the code inside MSALInstanceFactory, it is indicating that the service is undefined. impor ...

Guidance on Implementing Promises in Ionic 2 and Angular 2

Here are two functions that I need to implement: this.fetchQuizStorage(); this.retrieveQuizData(); fetchQuizStorage() { this.quizStorage.getAnswers().then(data => { return data; }); } retrieveQuizData() { this.quizData.getQuiz().t ...

Error: Code layer not located while utilizing "sam invoke local" in AWS

Currently, I am engaged in an AWS project where I am developing two lambda functions. Both of these functions rely on a common codebase stored in the node_modules directory, which is placed in a separate layer named AWS::Lambda::LayerVersion, not to be con ...

Slice an interactive div

I am currently working on setting up a horizontal sliding div for a menu. The layout consists of a left DIV that remains visible at all times, and a sliding DIV that appears horizontally when the menu is activated. My HTML code looks like this. <div id ...

Ways to selectively apply colors to particular rows within an AntD table

I'm attempting to apply different colors to entire rows depending on certain data values from the table's data source. I know that we can utilize rowClassName, but I'm not entirely clear on its functionality. If anyone could provide exampl ...

When attempting to access a static method in TypeScript, an error occurs indicating that the property 'users_index' does not exist on the type 'typeof UserApiController'

Just dipping my toes into TypeScript and attempting to invoke a function on a class. In file A: import userAPIController from "./controllers/customer/userAPIController"; userAPIController.users_index(); In file B: export default class UserApiControlle ...

What could be causing my Angular Ngrx app's state not to render properly on the application?

Is there a way to automatically render the state when the app loads without having to click a button? I am currently facing an issue where the state is empty until I manually trigger the click function by pressing a button. I have tried using this.store.se ...

Using string interpolation and fetching a random value from an enum: a comprehensive guide

My task is to create random offers with different attributes, one of which is the status of the offer as an enum. The status can be “NEW”, “FOR_SALE”, “SOLD”, “PAID”, “DELIVERED”, “CLOSED”, “EXPIRED”, or “WITHDRAWN”. I need ...