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

ためthisサイトを参照してください?どの角度バージョンを使用していますか – Rahul

+0

@Rahul angular 4 –

+0

angular 4.3.0以降HTTPインターセプタがサポートされています。したがって、角度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 {} 

あなたはHTTPインターセプタを検索しようとしなかった参照

+0

あなたが私の質問で言及した私の例であなたのコードをマップできますか? –

+0

このインターセプタファイルをプロジェクトに追加すると、インターセプタは常に、インターセプタでそれぞれのhttp要求と処理を傍受します。 – Rahul

+0

この問題を解決したいと考えています – Rahul

関連する問題