2017-09-25 75 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