Request for angular token

Asked

Viewed 65 times

0

How to put my Authorization token in my http request (GET). This is my current code:

import { Component } from '@angular/core';
import { Http } from '@angular/http';
import { HttpClientModule, HttpHeaders } from '@angular/common/http';

@Component({
  selector: 'app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
    title = 'Guilherme';
    url = 'https://URL.com'
    token = 'b7ff1...';

    constructor(http: Http) {       
        let stream = http.get(this.url, {
            headers: new HttpHeaders().set('Authorization', this.token),
        }).subscribe();
    }
}

webpack: Compiled successfully. ERROR in src/app/app.component.ts(28,36): error TS2345: Argument of type 'headers: Httpheaders;}' is not Assignable to Parameter of type 'Requestoptionsargs'

Types of Property 'headers' are incompatible. Type 'Httpheaders' is not Assignable to type 'Headers'. Property 'foreach' is Missing in type 'Httpheaders'.

1 answer

1

I believe your problem is happening because you are caring http module (@angular/http) while the Headers comes from another module (@angular/common/http).

By Angular team indication (due to future removal of the @angular/http module) you should import both from the module @angular/common/http, that should solve your problem.

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

@Component({
    selector: 'app',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})

export class AppComponent {
    title = 'Guilherme';
    url = 'https://URL.com'
    token = 'b7ff1...';

    constructor(http: HttpClient) {
        let stream = http.get(this.url, {
            headers: new HttpHeaders().set('Authorization', this.token),
        }).subscribe();
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.