2017-06-24 29 views
5

我正在嘗試非常簡單的angular 4 http請求。 當我檢查鉻開發人員工具,我看不到http頭。Angular 4不包含對http請求的頭文件

const headers: Headers = new Headers(); 
headers.append('Content-Type', 'application/json'); 
headers.append('Authorization', 'Bearer: 123213'); 
this.http.post('https://127.0.0.1:502', JSON.stringify(token), {headers: headers}).subscribe(); 

我錯過了什麼?

+0

檢查[這](https://stackoverflow.com/a/41133924/2545680) –

+0

@Maximus只是嘗試,並沒有工作。 :/ –

+0

我在回答中提供了一個示例,只是檢查了一下,它適用於我,我正在使用Angular v4.x –

回答

13

[email protected]開始,@angular/http模塊已棄用所有類。應該使用angular/common/httpRead here瞭解更多信息。

你可以這樣說:

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

export class AppComponent { 
    constructor(private http: Http) { 
     const headers = new Headers(); 
     headers.append('Content-Type', 'application/json'); 
     headers.append('authentication', `hello`); 

     const options = new RequestOptions({headers: headers}); 
     this.http.post(
      "http://localhost:3000/contacts", 
      JSON.stringify({id: 4, name: 'some'}), 
      options 
     ).subscribe(); 

你必須確保,你從@angular/http導入正確的對象:

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

如果您還沒有看到你頭文件,也有可能您使用的服務器不允許它們。當瀏覽器向另一個源發出請求時,它會發送access-control-headers-request頭來檢查服務器是否允許自定義頭。如果您的服務器未配置爲允許自定義標題,則不會在隨後的請求中看到它們。

+1

根據[文檔頭](https://angular.io/api/http/Headers) ,該類已棄用,建議使用[class * HttpHeaders *](https://angular.io/api/common/http/HttpHeaders)。我仍然無法使它工作,儘管(我的語法太過於無知),所以如果你想用非過時的類更新你的答案,那將是非常值得讚賞的。 – DonkeyBanana

+0

@DonkeyBanana,是的,@ angular/http'模塊已被棄用。現在應該使用'@ angular/common/http'。我會添加到答案。謝謝 –

0

將這個

constructor(private http: Http) { 
      this.headers = new Headers(); 
      this.headers.append('content-type', 'application/json'); 
    } 

和方法在這裏面

return this.http.post(url, jsonData, this.headers).map((resp: Response) => resp.json()); 
9

如果您使用的HttpClient而不是HTTP代碼應該是這樣的:

login(credintials: Authenticate): Observable<any> { 

    const body = { 
     username: credintials.username, 
     password: credintials.password, 
     grant_type: 'password', 
     client_id: credintials.client_id 
    }; 
    const headers = new HttpHeaders() 
     .set('Content-Type', 'application/x-www-form-urlencoded') 
     .set('Authorization', 'Basic loremlorem'); 

    return this.http.post(`${baseUrl}/uaa/oauth/token`, 
     body, 
     { 
      headers: headers 
     } 
    ); 
} 

如果params爲可選你應該添加這樣的參數:

let params: HttpParams = new HttpParams(); 
if (param) { 
    params = params.append('page', param.page); 
} 

源代碼如下所示:

/** 
* Construct a new body with an appended value for the given parameter name. 
*/ 
append(param: string, value: string): HttpParams;