1.我们首先定义一个服务 HttpInterceptorService
//http-interceptor.service.ts
import { Injectable,Inject } from '@angular/core';
import { Http,Request,RequestOptionsArgs,Response,RequestOptions,ConnectionBackend,Headers } from '@angular/http';
import 'rxjs/Rx';
import { Observable } from 'rxjs/Observable';
import { environment } from '../../../environments/environment';
import { StorageService } from './storage.service';
import { Router } from '@angular/router';
@Injectable()
export class HttpInterceptorService extends Http {
status = {
"status.400": "错误的请求。由于语法错误,该请求无法完成。",
"status.401": "未经授权。服务器拒绝响应。",
"status.403": "已禁止。服务器拒绝响应。",
"status.404": "未找到。无法找到请求的位置。",
"status.405": "方法不被允许。使用该位置不支持的请求方法进行了请求。",
"status.406": "不可接受。服务器只生成客户端不接受的响应。",
"status.407": "需要代理身份验证。客户端必须先使用代理对自身进行身份验证。",
"status.408": "请求超时。等待请求的服务器超时。",
"status.409": "冲突。由于请求中的冲突,无法完成该请求。",
"status.410": "过期。请求页不再可用。",
"status.411": "长度必需。未定义“内容长度”。",
"status.412": "前提条件不满足。请求中给定的前提条件由服务器评估为 false。",
"status.413": "请求实体太大。服务器不会接受请求,因为请求实体太大。",
"status.414": "请求 URI 太长。服务器不会接受该请求,因为 URL 太长。",
"status.415": "不支持的媒体类型。服务器不会接受该请求,因为媒体类型不受支持。",
"status.416": "HTTP 状态代码 {0}",
"status.500": "内部服务器错误。",
"status.501": "未实现。服务器不识别该请求方法,或者服务器没有能力完成请求。",
"status.503": "服务不可用。服务器当前不可用(过载或故障)。"
};
constructor(backend : ConnectionBackend, defaultOptions : RequestOptions,private router:Router,private storage : StorageService) {
super(backend, defaultOptions);
}
request(url : string | Request, options ? : RequestOptionsArgs) : Observable < Response > {
// typeof url == 'string' ? (url = environment.api + url) : (url.url = environment.api + url.url);
if (typeof url === 'string') {
url = (url.indexOf('assets/') != -1 ? environment.self : environment.api) + url;
} else {
url.url = (url.url.indexOf('assets/') != -1 ? environment.self : environment.api) + url.url;
//当我们才用这种方式来传headers的信息的时候下面的get,post等方法可以不写。
//下面的那些get,post等方法是为了解决没有把头部信息传递过去写的。采用下面这段代码可以注释掉下面的get,post等方法
//因为调用的request方法的时候http底层传递过来的是一个request对象。
//url.headers.append('Content-Type345345', 'application/json543534');
}
//options = options || new RequestOptions();
console.log("显示加载中。。。");
console.log(options);
return this.intercept(super.request(url, this.getRequestOptionArgs(options)));
}
get(url : string, options ? : RequestOptionsArgs) : Observable < Response > {
return super.get(url, this.getRequestOptionArgs(options));
}
post(url : string, body : any, options
?
: RequestOptionsArgs) : Observable < Response > {
return super.post(url, body, this.getRequestOptionArgs(options));
}
put(url : string, body : any, options
?
: RequestOptionsArgs) : Observable < Response > {
return super.put(url, body, this.getRequestOptionArgs(options));
}
delete(url : string, options
?
: RequestOptionsArgs) : Observable < Response > {
return super.put(url, this.getRequestOptionArgs(options));
}
//修改headers参数信息
getRequestOptionArgs(options ?: RequestOptionsArgs) : RequestOptionsArgs {
if(options == null) {
options = new RequestOptions();
}
if (options.headers == null) {
options.headers = new Headers();
}
options.headers.append('Content-Type', 'application/json');
options.headers.append("version",environment.version);
if (this.storage.get("token")) {
options.headers.append('token',this.storage.get('token'));
}
console.log(options);
return options;
}
//请求发生错误是提示信息
intercept(observable : Observable < Response >) : Observable < Response > {
return observable.catch((err, source) => {
console.log("关闭加载中。。。");
if (err.status < 200 || err.status >= 400) {
console.log('网络错误:' + err.status + ' - ' + this.status['status.' + err.status]);
//处理了当为 401 错误的时候我们清空localstorage里面的值,并让路由跳转
if(err.status === 401) {
this.storage.reomveOther();
this.router.navigate(['/login']);
}
return Observable.throw(err);
} else {
return Observable.throw(err);
}
}).map(value=>{
console.log("关闭加载中。。。");
return value;
});
}
}
在app.model 里面注入
// app.model.ts
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; // this is needed!
import { NgModule } from '@angular/core';
import { HttpModule, Http ,XHRBackend,RequestOptions} from '@angular/http';
import { TranslateService, TranslateModule, TranslateLoader } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
import { Router } from "@angular/router";
import { AppComponent } from './app.component';
import { CoreModule } from './core/core.module';
import { LayoutModule } from './layout/layout.module';
import { SharedModule } from './shared/shared.module';
import { RoutesModule } from './routes/routes.module';
import { ServiceModule } from './dnn/service/service.module';
import { HttpInterceptorService } from './dnn/service/http-interceptor.service';
import { StorageService } from './dnn/service/storage.service';
// https://github.com/ocombe/ng2-translate/issues/218
export function createTranslateLoader(http: Http) {
return new TranslateHttpLoader(http, './assets/i18n/', '.json');
}
//在httpinterceptorserveice 里面用那些服务需要注入进来 这块是主要的
export function interceptorFactory(xhrBackend : XHRBackend, requestOptions : RequestOptions,router: Router,storage:StorageService) {
let service = new HttpInterceptorService(xhrBackend, requestOptions,router,storage);
return service;
}
//主要结束
@NgModule({
declarations: [
AppComponent
],
imports: [
HttpModule,
BrowserAnimationsModule, // required for ng2-tag-input
CoreModule,
LayoutModule,
SharedModule.forRoot(),
RoutesModule,
ServiceModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: (createTranslateLoader),
deps: [Http]
}
})
],
providers: [
//这块是主要的
{
provide: Http,
useFactory: interceptorFactory,
//在httpinterceptorserveice 里面用那些服务需要注入进来
deps: [XHRBackend, RequestOptions,Router,StorageService]
}
//主要结束
],
bootstrap: [AppComponent]
})
export class AppModule { }
这样我们使用调用http时,会找写的这个服务。
//userApiservice
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
@Injectable()
export class UserapiService {
constructor(private http:Http) { }
/**
* 登录
* @param user 用户对象 用户名,密码
*/
apilogin(user:object):Promise{
return this.http.post('pub/login',user).toPromise().then(response=>{
return response.json() as any[];
});
}
}
我们调用userapiservice里面的apilogin方法时会走我们定义的拦截器服务。