angularangular2.0Angular: Zero to Hero

Angular2 Http拦截器 Interceptor 实现

2016-10-23  本文已影响6804人  chunxueer

是这样的,由于前面文章中前端和后台整合的不是太好,开发阶段前端和后端肯定是分开的,这样就导致前端请求数据时地址不对。于是我准备做一个配置文件,在请求时更改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

上一篇下一篇

猜你喜欢

热点阅读