Angular2 Http攔截器 Interceptor 實現

是這樣的,由于前面文章中前端和后臺整合的不是太好,開發階段前端和后端肯定是分開的,這樣就導致前端請求數據時地址不對。于是我準備做一個配置文件,在請求時更改url地址,便有了Http攔截器的需求。
網上Angular1攔截器寫法比較多,Angular2比較少,github一下,看到確實有大神實現了Angular2的實現。畢竟是大神,不屑與代碼細節說明,沒有現成的例子,只有相關說明,于是開始按照大神說明來coding 了。
大半夜了,寫的真心累csnd編輯器有問題。
使用項目地址 https://github.com/voliva/angular2-interceptors

1、在項目的根目錄執行,安裝ng2-interceptors

npm install ng2-interceptors --save

2、創建類文件src/app/core/http/server.url.interceptor.ts

import { Interceptor, InterceptedRequest, InterceptedResponse } 
from 'ng2-interceptors';

export class ServerURLInterceptor implements Interceptor {
    public interceptBefore(request: InterceptedRequest): InterceptedRequest {
        // 修改請求
      request.url = "http://localhost:8080/ovit-java-framework/"+request.url;
      console.log("intercept url:"+request.url);
      return request; 
    }
    public interceptAfter(response: InterceptedResponse): InterceptedResponse {
        return response;
    }

}

3、修改網絡請求服務,將注入的Http 換成 InterceptorService

constructor(private http: Http) { }
constructor(private http: InterceptorService ){ }

內容如下src/app/core/auth/auth.service.ts

import { Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';
import { InterceptorService  } from 'ng2-interceptors';
import 'rxjs/add/operator/toPromise';

import { Session } from './session'; 
import { User } from '../user/user'; 

@Injectable()
export class AuthService {

  private headers = new Headers({'Content-Type': 'application/json'});
  session: Session;
  constructor(private http: InterceptorService ) { }
 
  // 登陸
  private url_authLogin = 'auth/login';
  login(account:string,password:string):Promise<User> {

        console.log("登陸:"+account+","+password);
    return this.http.post(this.url_authLogin,
                JSON.stringify({account:account,password:password}))
               .toPromise()
               .then(response => response.json().data as User  )
               .catch(this.handleError); 
  } 

  // 注銷
  private url_authLogout = 'auth/logout'; 
  logout(userId: string): Promise<void> { 
     this.session.user  = null;
    return this.http.post(this.url_authLogout,
       JSON.stringify({userId:userId}), {headers: this.headers})
      .toPromise()
      .then(() => null)
      .catch(this.handleError); 
  }
  private handleError(error: any): Promise<any> {
    console.error('發生錯誤', error); 
    return Promise.reject(error.message || error);
  }
}

4、修改src/app/app.module.ts

import { provideInterceptorService  } from 'ng2-interceptors'; 
import { ServerURLInterceptor } from './core/http/server.url.interceptor';

  providers: [
    LocalStorage,AuthService,UserService,ServerURLInterceptor, 
    provideInterceptorService([
      ServerURLInterceptor
    ]) 
  ],

全部內容如下

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import {NgbModule} from '@ng-bootstrap/ng-bootstrap';

import { provideInterceptorService  } from 'ng2-interceptors'; 
import { ServerURLInterceptor } from './core/http/server.url.interceptor';

import './rxjs-extensions';

import { LocalStorage } from './core/common/local.storage';

import { AppComponent } from './app.component';
import { IndexComponent } from './index/index.component';
import { MainComponent } from './main/main.component';
import { HelpComponent } from './help/help.component';

import { Session } from './core/auth/session';

import { AuthService } from './core/auth/auth.service';
import { UserService } from './core/user/user.service';

import { AppRoutingModule }     from './app-routing.module';

@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    AppRoutingModule, 
    NgbModule.forRoot()
  ],
  declarations: [
    AppComponent,IndexComponent,MainComponent,HelpComponent
  ],
  providers: [
    LocalStorage,AuthService,UserService,ServerURLInterceptor, 
    provideInterceptorService([
      ServerURLInterceptor
    ]) 
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

我的其它博客將同步更新:
CSDN
簡書
github

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 173,065評論 25 708
  • WebSocket-Swift Starscream的使用 WebSocket 是 HTML5 一種新的協議。它實...
    香橙柚子閱讀 24,057評論 8 183
  • 我 你 他 愛 ? 愛 不知道啊 饑人谷
    Komolei閱讀 125評論 0 0
  • 身邊每每有一些灑脫之士,常常將諸如“錢財乃身外之物,生不帶來死不帶去,其一點也不看重錢財,工作也不是因為錢”之...
    胡美云閱讀 230評論 1 0
  • 1)商量;協商,協議,磋商;商談;商定,一致的意見。〔話し合い。協議する。口頭の商談。相談して決める〕。 友達と相...
    萌囧囧閱讀 906評論 6 0