What could be causing my Angular 7 header to be unresponsive?

I am facing issues with my http, header, and RequestOption in the API. I am working with Angular 7.1 and have tried various methods to resolve the problem without success.

The error message I am receiving is:

The token is not being passed in the header

This is the code snippet that I am currently using:

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

@Injectable({
    providedIn: 'root'
})
export class UrlrequestService {
    public headers = new Headers({ 'Content-Type': 'application/json'});
    API:any = "http://api-url";
    constructor(public http: Http) { }

    get(url) {  
        this.headers.set('Authorization','Token  '+localStorage.getItem('token'))
        let options = { headers: this.headers };
        console.log(options)
        return this.http.get(this.API+url,options);
    }

Answer №1

When working with Angular 7, remember to import HttpClient and HttpHeaders from @angular/common/http. To pass the token, make sure to use Bearer. Here's an example of how you can do this:

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

// ...

httpOptions;
api_path:any = "http://api-url";

constructor(public http: Http) {}


// ...
this.httpOptions = {
  headers: new HttpHeaders({
  'Content-Type':  'application/json',
  'Authorization': 'Bearer ' + localStorage.getItem('token')
  })
};

Answer №2

When sending HTTP Headers, it's important to keep in mind that the tokens should be of type Bearer. Therefore, the authorization header line should look like this:

this.headers.set('Authorization','Bearer '+localStorage.getItem('token'))

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

Transform event binding using PrimeNG Elements and Angular

My challenge lies in dynamically binding change events within the PrimeNG TreeTable by defining functions on my columns. I've noticed that attempting to bind the change event dynamically with my columns doesn't seem to work properly inside the Tr ...

How can you properly structure chainable functions in Angular?

Recently, I've been working on developing custom functions for my Angular application. Following the official guidelines, I have created an independent library. My goal is to create chainable functions similar to this: var obj = { test : function( ...

Distinguishing between type assertion of a returned value and defining the return type of a function

What distinguishes between performing a type assertion on a function's return value and explicitly typing the return value in the function signature? Let's consider only simple functions with a single return statement. interface Foo { foo: numbe ...

Error: The 'Store' property is not found in the '{}' type but is needed in the 'Readonly<Istore>' type. TS2741

Can you assist me in resolving this issue? I am attempting to pass my store as props to the component, but I keep encountering the following error: Type error: Property 'Store' is missing in type '{}' but required in type 'Readon ...

Creating mandatory reactive form fields in Angular 11's HTML code based on conditions

I am facing an issue with two select/dropdown fields in my form. The second dropdown field should render based on a condition *ngIf="selectedStdntList?.packages". However, the problem is that the submit form function stops working even when the c ...

Navigating through tslint: adhere to the one-variable-per-declaration rule

What is the best way to write code following this rule? let exampleArray = [...]; for (let j = 0, k = exampleArray.length; j < k; j++) { ... } ...

Building a hierarchical tree structure using arrays and objects with Lodash Js

I am attempting to create a tree-like structure using Lodash for arrays and objects. I have two arrays, one for categories and the other for products, both with a common key. The goal is to organize them into a tree structure using string indexing. let ca ...

Ways to properly exit a function

What is the best way to pass the apiKey from the createUser function in User.ts to Test.ts in my specific scenario? User.ts interface User { url: string, name: string, } class User{ async createUser( user: User ):Promise<void> { le ...

Customize the form using a custom component in react-hook-form: setting a default value

I have been learning ReactJS + TypeScript for 3 months now. Recently, I have a question about using react-hook-form (v7) to edit a form. I want to integrate my custom component into the form and I managed to do it on my own! Here is a snippet of my form p ...

Do we truly need to demolish components that are dynamic in nature?

const validReportComponents = { default: DefaultTemplateComponent } @ViewChild('container', { read: ViewContainerRef }) containerRef: ViewContainerRef; private _componentReference: ComponentRef<any>; constructor( public activeModal: Ngb ...

Issue with form control not functioning properly after implementing custom validation within the form group

Here is my group setup - this.fb.group( {email: new FormControl('')}, { validators: [ formGroup => {email:"some error"}] } ); This is how I have structured my form: <form [formGroup]="formGroup" ...

A guide on dynamically displaying a component within another component using Angular2

I am currently facing a challenge where I need to dynamically display a component within another component. When a particular record is clicked, I want to replace that record with the selected component and perform specific actions on it. Does anyone have ...

Angular's isteven-multi-select Component: A Versatile Selection Tool

Is it possible to utilize isteven-multi-select with ng-model? My goal is to have certain items appear as chosen when the page loads using the isteven-multi-select module. I've tried using ng-model in the HTML page to populate the isteven-multi-select ...

implementing an event listener in vanilla JavaScript with TypeScript

Can anyone help me figure out how to correctly type my event listener in TypeScript + Vanilla JS so that it has access to target.value? I tried using MouseEvent and HTMLButtonElement, but I haven't been successful. const Database = { createDataKeys ...

What could be the reason for encountering a Typescript ts(2345) error while trying to pass a mocked constant to .mockResolvedValue()?

Within my test.tsx file, I have the following code snippet: test('Photos will load', async () => { const mockCuratedPhotos = jest.spyOn(endpoints, 'getCuratedPhotos'); mockCuratedPhotos.mockResolvedValue(mockPhotos); awa ...

Retrieve data from a URL using Angular 6's HTTP POST method

UPDATE: Replaced res.json(data) with res.send(data) I am currently working on a web application using Angular 6 and NodeJS. My goal is to download a file through an HTTP POST request. The process involves sending a request to the server by calling a func ...

Transferring information from a service to a parent component, and subsequently passing it to a child component

Hello everyone, I am a beginner with Angular and I seem to have run into an issue that I can't figure out. In my parent component, I am attempting to pass the weekly variable to my child component but it doesn't seem to be working as expected. H ...

Having trouble importing zone.js in Angular 14 and Jest 28

I am currently in the process of updating to Angular 14. Everything is going smoothly except for setting up jest. Since I have Angular 14 libraries included in my build, I need to utilize jest-ESM support. Below is my configuration: package.json { &qu ...

Webpack is throwing an error: TypeError - It seems like the object prototype can only be an object or null, not

My Angular 4 application is utilizing webpack. Strangely, I encounter an error when attempting to run it on my Amazon server, although it works perfectly fine on my local machine. Any insights into why this might be occurring? Thank you very much for any ...

Type Assertion for Optional Values in TypeScript

Just confirming the proper way to handle situations like this. My current setup involves using Vue front-end with Typescript, sending data to an API via axios. I've defined reactive objects as follows: const payload = reactive({ name: '' ...