angular4 http标头,如何设置?

时间:2017-07-27 08:40:20

标签: angular

import { Injectable } from '@angular/core';
import { Http, Headers, Response, RequestOptions,  } from '@angular/http';
@Injectable()
export class RoleService {
    headers = new Headers({"Content-Type": "application/json"});
     options = new RequestOptions({ headers: this.headers });
     constructor(private http: Http) {  }

    getRoleList(data) {
         return this.http.post('http://192.168.10.178:9080/role/getRole', data, this.options)
                .toPromise()
                .then(res => res.json().data)
                .then(data => { return data; });
    }
}

https://i.stack.imgur.com/nPiK8.png

救救我!!怎么解决这个???

3 个答案:

答案 0 :(得分:5)

尝试

export class RoleService {
  options: RequestOptions;

  constructor(private http: Http) {
    let headers: any = new Headers();
    headers.append('Content-Type', 'application/json');

    this.options = new RequestOptions({ headers: headers });
  }

// ........

答案 1 :(得分:0)

它可能会解决您的问题

import { Injectable } from '@angular/core';
import { Http, Headers, Response, RequestOptions,  } from '@angular/http';
@Injectable()
export class RoleService {
     constructor(private http: Http) {  }

    getRoleList(data) {
     let headers = new Headers({"Content-Type": "application/json"});
     let options = new RequestOptions({ headers: headers });
         return this.http.post('http://192.168.10.178:9080/role/getRole', data, this.options)
                .toPromise()
                .then(res => res.json().data)
                .then(data => { return data; });
}}

答案 2 :(得分:0)

在Angular 4.3版本之后,HttpClientModuleHttpClientHttpHeadersHttpParamsHttpRequest一起被引入,并且某些方法已被弃用例如RequestOptions

您可以使用HttpClientModule中的@angular/common/http

import { HttpClient, HttpRequest, HttpParams, HttpHeaders } from '@angular/common/http';
export class AppComponent {
    constructor(private http: HttpClient){}
    headers = new HttpHeaders({"Content-Type": "application/json"});

    callAPI(){
         return this.http.get(URL,{headers}).subscribe(data=>{
             console.log(data);
         });
    }
}

您还可以参考: - https://angular.io/api/common/http/