简体   繁体   中英

angular2 http request with headers, do not send

Quite new to angular2 I try to build a data service and I want to add to each request headers

here is what I try but the headers won't be sent

import { Injectable } from '@angular/core';
import { Http, Response, Headers } from '@angular/http';
import 'rxjs/add/operator/map'
import { Observable } from 'rxjs/Observable';
import { Configuration } from '../app.constants';
import { AuthenticationService } from '../services/';

@Injectable()
export class DataService {

    private actionUrl: string;
    private headers: Headers;
    private token;


    constructor(private _http: Http,
                private _configuration: Configuration

                //private authenticationService: AuthenticationService

    ) {

        var currentUser = JSON.parse(localStorage.getItem('currentUser'));

        if(currentUser)
            this.token = currentUser.token;

        this.actionUrl = _configuration.ServerWithApiUrl + 'patients';

        this.headers = new Headers();

        this.headers.append('Content-Type', 'application/x-www-form-urlencoded');
        this.headers.append('Accept', 'application/json');
        this.headers.append('Authorization', 'Bearer ' + this.token);
    }

    public GetAll = (): Observable<any> => {
        return this._http.get(this.actionUrl, this.headers).map((response: Response) => <any>response.json());
    }
}

how to do it properly or why this do not work?

您需要在“ this.header”周围加上“ {}” ...,如下所示:

return this.http.get(this.constants.accountLocalUrl, { headers: headers })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM