Issue with Typescript/Angular2: http.post failing to set headers

Having trouble with transmitting headers in a json post from Angular2 beta 8:

import { RequestOptions, RequestMethod, Headers, RequestOptionsArgs, Http } from 'angular2/http';

// ...
let headers = new Headers(),
    body = JSON.stringify({ identifier, password });

headers.append('Content-Type', 'application/json');
headers.append('Accept', 'application/json');
let opts:RequestOptionsArgs = { headers: headers };

this.http.post(this.baseUrl + 'auth/login', body, opts)
    .subscribe(
         data => console.log(data),
         err => console.log(err.json().message),
         () => console.log('Authentication Complete')
    );

However, the XHR call in Chrome is not showing these headers. Debugging in Chrome indicates that the Content-Type header is labeled as Provisional Headers are Shown and shows

Content-Type:text/plain;charset=UTF-8
. It seems like the header values are correct though:

console.log(headers.get('Content-Type')) // => 'application/json'
console.log(headers.get('Accept'))       // => 'application/json'

The issue seems to be using RequestHeaders instead of Headers. Not sure why it didn't throw an error.

Answer №1

In order to successfully make use of the Headers class, ensure that you import it correctly (as shown below) within your codebase from the angular2/http package:

import {
  RequestOptions,
  RequestMethod,
  RequestHeaders,
  RequestOptionsArgs,
  Http,
  Headers // <------
} from 'angular2/http';

// ...
let headers = new Headers(),
body = JSON.stringify({ identifier, password });

If you require further clarification, please refer to this question for additional information:

  • Angular2/Http (POST) headers

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

Typescript: maintain object value enforcement while preserving explicit keys

One interesting observation I had is that in the example below, I was successful in extracting explicit keys from the object, but had difficulty enforcing its values: const myCollection = { a: {test: 1}, b: {test: 2}, c: {text: 3} // no error ...

Using Angular: A guide to importing an external library not found in NPM via Bower

I am trying to utilize a library that I obtained from a bower repository. Since it is not available in NPM, I am looking for ways to make it work and integrate it into my application. Here is what my structure looks like: https://i.sstatic.net/RUhsA.png ...

Anglar2-useful-swiper does not automatically advance slides

I've been working on integrating the angular2-useful-swiper plugin into a single page application for image display, complete with auto rotation. However, I'm encountering an issue where the images are not transitioning as they should, and instea ...

Angular class requires multiple class members and validators for MatSelection List to be bound with Formbuilder

Could you please guide me on how to connect the Google Angular Materials mat-selection-list with the FormBuilder? We have the following class and are attempting to utilize Reactive Form Builder for this purpose. While we are aware of how to link data class ...

The ng-content within the ng-template is visible exclusively within a single ng-container

I am currently developing a flip panel consisting of three parts: panel-tool-bar panel-front panel-back The tool-bar contains a fixed element, the flip button. Within my flip-panel.component, I have an ng-template for the tool-bar to ensure it is displ ...

Function to convert a property with a default value to an optional generic type

I created a function to validate FormData objects with Zod, using a generic type for flexibility across schemas. Here's the validate function: export function validate<T>( formData: FormData, schema: z.ZodSchema<T> ): { validatedD ...

Is it possible to use square brackets in conjunction with the "this" keyword to access a class property using an expression?

export class AppComponent implements OnInit { userSubmitted = false; accountSubmitted = false; userForm!: FormGroup; ngOnInit(): void {} onSubmit(type: string): void { this[type + 'Submitted'] = true; if(this[type + 'For ...

Is it possible to transfer files using Angular 2?

Currently, I am utilizing Angular2 and TypeScript to transmit a file in conjunction with JSON Data to a designated server. HTML Code <input type="file" class="form-control" name="avatar" id="uploadyour" name="uploadyour" #uploadyour="ngModel" [(ngMode ...

Having difficulty selecting an item from the MaterialUI package

While trying to utilize the MaterialUI Select component with typescript/reactjs, I encountered an issue during the instantiation of the Select element. The error message I'm receiving states: Type 'Courses' is missing the following properti ...

The use of credentials is not allowed when the ‘Access-Control-Allow-Origin’ CORS header is set to ‘*’

My Java web application makes CORS requests where the browser performs an OPTIONS preflight before the actual request. The format of each request is as follows: Host: localhost:8080 User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:63.0) Gecko/2 ...

What could be the reason for tsc providing such confusing error messages upon revealing transitive implementation types?

In my project, I am dealing with a node module A that relies on another node module B, both of which are written in Typescript. Module B uses bluebird as its Promise implementation and returns Promises to module A. While module B has typings for bluebird, ...

Updating real-time data in Angular 2+ without needing to refresh the page based on certain conditions

When receiving a transaction from the API service, my code is designed to keep reloading and subscribing to the transaction until its status changes to 'completed' or 'rejected'. However, I am encountering an issue where the page appear ...

Changing the time format to ISO in order to fill the ion-datetime component within Ionic 2

I have this snippet of code in my HTML file: <ion-datetime [(ngModel)]="time" formControlName="time" displayFormat="hh:mm a"></ion-datetime> I am trying to populate the ion datetime element with data retrieved from the server. The response fr ...

Tips for creating a state change function using TypeScript

Imagine the temperature remains constant for 20 minutes, but at the 21st minute, it changes. The state change is determined by a programmable state change function. How can I create a function to calculate the difference in state change? if(data.i ...

Run a single feature file in Protractor by utilizing a specific tag

Is it possible to run just one feature file in Protractor? I am aware that I can specify the file in protractor.conf.js, but I have come across a different solution involving the use of a tag: To single out a specific feature file, you would include a tag ...

Bringing in additional types with the primary import using import/require

I am currently creating a definition file for Airtable, and I have encountered an issue with the way they export their classes. They only provide one class like this: ... module.exports = Airtable; As a result, my airtable.d.ts file looks something like ...

Leverage async-await in conjunction with subscription

I am struggling with a tangled mess of code known as 'callback hell'. Can someone please guide me on how to make use of async-await to simplify the debugging process and tidy up this situation? this.ws.call('vm.image_path', ['Ran ...

When processing JSON data, Typescript is unable to interpret a map<string,string> structure

I am currently working with Angular5 within a spring boot application and I am attempting to retrieve a Map object in JSON format. Spring : //sample method return ResponseEntity.ok((new Gson()).toJson(/*My map object*/)); Angular5 : sql_list = new Map& ...

Customizing dropzone color while dragging an image in Angular

I have been using Angular and created an image input field. Within this input field, I implemented a dropzone that allows users to drag files into it. Is there a way for me to modify the background of the dropzone when a file is being dragged into it? Thi ...

Serverless-offline is unable to identify the GraphQL handler as a valid function

While attempting to transition my serverless nodejs graphql api to utilize typescript, I encountered an error in which serverless indicated that the graphql handler is not recognized as a function. The following error message was generated: Error: Server ...