Code error TS2345 occurs when assigning the argument of type '{ headers: HttpHeaders; }' to a parameter of type 'RequestOptionsArgs'. This indicates a mismatch in the type of data being passed, causing an

Upon running ionic serve, these are the results that I am encountering. My setup consists of Ionic4 version with Angular 8.

While executing the command, this error appears: src/app/home/home.page.ts:60:77 - error TS2345: Argument of type '{ headers: HttpHeaders; }' is not assignable to parameter of type 'RequestOptionsArgs'. [ng] Types of property 'headers' are incompatible. [ng] Type 'HttpHeaders' is missing certain properties from type 'Headers': forEach, values, toJSON, entries, mayBeSetNormalizedName [ng] 60 this.http.post("http://localhost/android/Api.php?apicall=signup", postData,options) [ng]

sendPostRequest() {
  
    let headers = new HttpHeaders();
    
    headers.append("Accept", 'application/json');
    headers.append('Content-Type', 'text/plain');
    let options = {
        headers: headers
    }
    

    /*
         if (this.authService.checkAuth()) {
             const token = 'something';
             headers = headers.set('Authorization', `Bearer ${token}`);
         }
      const authReq = req.clone({ headers });*/
    
    
    let postData = {
      
        "username": "Customer004",
        "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5734222423383a322567676317323a363e3b7934383a">[email protected]</a>",
        "password": "0000252525",
        "gender": "male",
    }
    
    /*this.http.post("http://localhost/android/Api.php?apicall=signup", postData, requestOptions)
      .subscribe(data => {
        console.log(data['_body']);
       }, error => {
        console.log(error);
      });*/
    
    
    var options = {
        headers: new HttpHeaders({
            'Content-Type': 'application/json'
        })
    };
    
    
    this.http.post("http://localhost/android/Api.php?apicall=signup", postData, options)
        .subscribe(data => {
            console.log(data);
        });
        
}

package.json

{
  "name": "registration",
  "version": "0.0.1",
  "author": "Ionic Framework",
  "homepage": "https://ionicframework.com/",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/common": "~8.1.2",
    "@angular/core": "~8.1.2",
    "@angular/forms": "~8.1.2",
    "@angular/http": "^7.2.16",
    "@angular/platform-browser": "~8.1.2",
    "@angular/platform-browser-dynamic": "~8.1.2",
    "@angular/router": "~8.1.2",
    "@ionic-native/core": "^5.0.0",
    "@ionic-native/splash-screen": "^5.0.0",
    "@ionic-native/status-bar": "^5.0.0",
    "@ionic/angular": "^4.7.1",
    "core-js": "^2.5.4",
    "rxjs": "~6.5.1",
    "tslib": "^1.9.0",
    "zone.js": "~0.9.1"
  },
  "devDependencies": {
    "@angular-devkit/architect": "~0.801.2",
    "@angular-devkit/build-angular": "~0.801.2",
    "@angular-devkit/core": "~8.1.2",
    "@angular-devkit/schematics": "~8.1.2",
    "@angular/cli": "~8.1.2",
    "@angular/compiler": "~8.1.2",
    "@angular/compiler-cli": "~8.1.2",
    "@angular/language-service": "~8.1.2",
    "@ionic/angular-toolkit": "^2.1.1",
    "@types/jasmine": "~3.3.8",
    "@types/jasminewd2": "~2.0.3",
    "@types/node": "^8.9.5",
    "codelyzer": "^5.0.0",
    "jasmine-core": "~3.4.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~4.1.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~2.0.1",
    "karma-jasmine-html-reporter": "^1.4.0",
    "protractor": "~5.4.0",
    "ts-node": "~7.0.0",
    "tslint": "~5.15.0",
    "typescript": "~3.4.3"
  },
  "description": "An Ionic project"
}

Answer №1

Make sure to include the necessary import statement in your Angular project:

import { Http, Headers, RequestOptions } from '@angular/http';
.

The Dependency Injection from http is functioning correctly. You can now utilize RequestOptions like this:

sendPostRequest() {
    let headers = new Headers({'Content-Type': 'application/json'});
    // headers.append('Content-Type', 'text/plain');
    // If unsure about the necessity of this append operation.

    let options = new RequestOptions({ headers: headers });

    const postData = {
        "username": "Customer004",
        "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fc9f898f889391998eccccc8bc99919d9590d29f9391">[email protected]</a>",
        "password": "0000252525",
        "gender": "male",
    }

    this.http.post("http://localhost/android/Api.php?apicall=signup", postData, options)
        .subscribe(data => {
            console.log(data);
        });
}

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

Determining if an item is empty, undefined, or null in Angular: a guide

I received a .json file structured as data [0 ... n]. Each position in the data array contains an object with various attributes, such as: {photo1, photo2, photo3 ... photoN} For a visual representation of how the json file is formatted, you can check ...

Mono repo project utilizing Angular 4+ and Typescript, enhanced with Bootstrap styling

Looking for a project to practice with Angular 4+ using Typescript and a Bootstrap template. Hoping for a setup where I can just run npm install and ng serve to start. Any recommendations for mono repos would be highly valued! ...

Steps to deactivate a button in an Angular reactive form upon submission

I am working with Angular reactive forms and I need to implement a functionality where the button is disabled and its label changes after it has been clicked or submitted. Any suggestions on how to achieve this? ...

When attempting to navigate to the index page in Angular, I encounter difficulties when using the back button

I recently encountered an issue with my Angular project. On the main index page, I have buttons that direct me to another page. However, when I try to navigate back to the index page by clicking the browser's back button, I only see a white page inste ...

Tips for resolving issues with mat-autocomplete during scrolling

When I open the mat-autocomplete and scroll down the page, I would like for the mat-autocomplete to stay in place. ...

"Having trouble subscribing? The first attempt doesn't seem to be working

I'm currently working on some TypeScript code that searches for the nearest point around a user in need of car assistance by checking a database. Once the nearest point is identified, the code retrieves the phone number associated with it and initiate ...

Error encountered when attempting to utilize ngTemplate to embed filter within a table

I am facing an issue with a component that includes a primeng table. Within a table row, I have an ng-container to project a p-columnFilter into the table from an external source. However, when trying to pass the filter into the template, I encounter a Nul ...

Modify the color of the matSnackbar

I'm having trouble changing the snackbar color in Angular using Angular Material. I tried using panelClass in the ts file and adding it to the global css, but the color remains unchanged. Any suggestions on how to resolve this? I am still new to this ...

Having trouble with Angular redirecting to the incorrect URL?

Currently delving into the world of Angular, I am eager to create a straightforward application where users can effortlessly switch between two components. The issue arises when attempting to navigate back from the navbar to the login component: <a rout ...

Testing units in Angular using different sets of test data

When it comes to unit testing a C# method with different sets of data, the Theory and InlineData attributes can be used to pass multiple inputs for testing purposes. [Theory] [InlineData("88X", "1234", "1234", "1234")] [InlineData("888", "123X", "1234", " ...

I have encountered limitations with useFormik where it does not accept null values for initialValues, even while utilizing a validationSchema

I am currently utilizing the useFormik hook to handle my form. The userId field is a select, so by default its value is set to null. However, my validationSchema requires this field to be populated before submission. const formik = useFormik<ApiCredit ...

Modify the CSS for the selected values in an angular material multi-select component

I am looking to customize the CSS for selected values in a material multi select. <mat-form-field class="mat-form-field-fluid"> <mat-select placeholder="User Permissions" [(value)]="selectedPermissions" multipl ...

There was an issue with the layout detection in Angular. The app-layout selector could not find a matching element in the code

Currently diving into the world of Angular and embarking on my first project, I've hit a roadblock. After initiating a terminal with the server, all I get is a blank page when I load my browser. Upon inspecting the page using f12, an error message pop ...

The silent refresh functionality is currently not functioning as expected in Angular's OAuth OIDC implementation

In my Angular SPA, I am attempting to silently refresh the access token. The authentication with ADFS has been successfully completed and everything is functioning properly. Below is the configuration that I have implemented: oauthService.configure({ ...

Models in Typescript that are interrelated with Loopback

I'm currently working on defining connected models including the HasMany relationship in the context of @types/loopback definitions My approach involves creating an interface for HasMany and its implementation: interface IHasMany { /** ...

After updating the file path, the Next.Js module couldn't be located: Module not found – Unable to

After relocating the EmptyTable.tsx file from its original directory at views/forms-tables/tables/react-table/EmptyTable to a new location at components/Tables/EmptyTable, I encountered a persistent issue. Despite updating the import path in my code to mat ...

Using Object.defineProperty in a constructor has no effect

I recently revamped my three.js project and ran into a peculiar issue where all objects were being rendered with the same geometry and material. Upon further investigation in the debugger, I narrowed down the problem to this constructor: function Geometry ...

How to effectively implement form-control with mat-radio-group?

UPDATE: Check out my code on stackblitz I'm facing an issue with my form layout. The form control rows are overlapping with the radio button rows. I need help to resolve this problem. Here is a snippet of my code: <form [formGroup]="formGroup" (n ...

Angular 6: Exploring the Challenges of Extending Services Without Sacrificing the Functionality of ChildService

As I was developing multiple angular REST-services for my frontend, I came up with the idea of creating a base class BaseRestService to handle common functionalities like headers and helper functions. However, I encountered TypeErrors when trying to call ...

Develop an asynchronous thunk with TypeScript in Redux Toolkit, utilizing the features of rejectWithValue and Payload types for handling errors

Struggling to integrate an authentication slice into Redux Toolkit using TypeScript, facing errors related to rejectWithValue and action payload types. Utilizing Axios and following the documentation, but TypeScript is still flagging issues in my code. im ...