2017-09-25 74 views
0

我想爲所有請求設置標題。不想一次又一次地爲每個請求頭像我有這樣Angular Rest Api標題調用問題

public update(student: Student): Promise<Student> 
{ 
    let headers = new Headers(); 
    headers.append('Content-Type', 'application/json'); 
    headers.append('authentication', `${student.token}`); 

    const url = `${this.studentsUrl}`; 

    return this.http 
     .put(url, JSON.stringify(student), { headers: headers }) 
     .toPromise() 
     .then(() => student) 
     .catch(this.handleError); 
} 

代碼,所以有沒有辦法從中我可以設置通用頭爲每個請求?

+0

您是否試過搜索http攔截器?您正在使用的角度版本 – Rahul

+0

@Rahul角度4 –

+0

角度4.3.0以上版本支持HTTP攔截器。所以如果你使用的角度是4.3.0+,那麼攔截器是最好的選擇。在角度4.3.0以下看到我的回答在 – Rahul

回答

0

UPDATE

要添加下面的角4.3通用的頭,你可能需要開發定製服務。 請參閱this答案,它解釋了角4.3之前的最佳解決方案。

你好你可以試試HTTP攔截:

注意:HTTP攔截器是由角4.3+

這是支持文件攔截

import { Injectable, NgModule} from ‘@angular/core’; 
import { Observable } from ‘rxjs/Observable’; 
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from ‘@angular/common/http’; 
import { HTTP_INTERCEPTORS } from ‘@angular/common/http’; 
@Injectable() 
export class MyInterceptor implements HttpInterceptor { 
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { 
     const dupReq = req.clone({ headers: req.headers.set(‘Consumer-Secret’, ‘some sample key’) }); 
     return next.handle(dupReq); 
    } 
}; 

和應用程序。 module.ts:

import { BrowserModule } from '@angular/platform-browser'; 
import { NgModule } from '@angular/core'; 

import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http'; 
import { MyInterceptor } from './interceptors/my.interceptor'; 


@NgModule({ 
    declarations: [AppComponent], 
    imports: [BrowserModule, HttpClientModule], 
    providers: [ 
    { provide: HTTP_INTERCEPTORS, useClass: MyInterceptor, multi: true } 
    ], 
    bootstrap: [AppComponent] 
}) 
export class AppModule {} 

請參閱this網站僅供參考

+0

你可以映射你的代碼在我提到的問題嗎? –

+0

當你在你的項目中添加這個攔截器文件;攔截器將總是攔截每一個http請求並處理你在攔截器中寫的任何東西 – Rahul

+0

希望這個問題能夠解決你的問題 – Rahul