摘要:初衷之前看到正式發(fā)布了,過去看了下,感覺不錯,于是入坑。不過思路還是可以借鑒的。嘗試以下第一篇鏈接第二篇鏈接第三篇里寫法過時了按照上述代碼,寫法與不同,不知道怎么改。
初衷
之前看到angular2正式發(fā)布了,過去看了下,感覺不錯,于是入坑。
使用過程中想寫一個像angular1那樣的攔截器,一路坎坷啊
.factory("HttpRequestInterceptor", ["$q", "$injector", "ConfigService", "DialogService", function($q, $injector, ConfigService, DialogService) { return { request: function(config) { if (config.method === "POST") { config.timeout = 60000; if (config.data === undefined) { config.data = { nologin: 999 }; } else { config.data.nologin = 999; } } return config; }, requestError: function(rejection) { DialogService.alert("發(fā)送請求失敗,請檢查網(wǎng)絡(luò)"); return $q.reject(rejection); }, response: function(resp) { if (resp.data.code !== undefined && resp.data.code !== 0) { if (resp.data.code === 5003) { var stateService = $injector.get("$state"); stateService.go("login", {}, { reload: true }); } else { DialogService.alert(resp.data.msg); } } return resp; }, responseError: function(rejection) { console.log(rejection); if (rejection.status === 0) { DialogService.alert("請求響應(yīng)錯誤,請檢查網(wǎng)絡(luò)"); } else if (rejection.status === 500) { DialogService.alert("服務(wù)器出錯"); } else { DialogService.alert("請求失敗,請檢查網(wǎng)絡(luò)"); } return $q.reject(rejection); } }; }])Angular2中沒有提供,需要自己實現(xiàn)
去Stackoverflow上搜了好久,有相關(guān)內(nèi)容是不錯,但過時了。不過思路還是可以借鑒的。
嘗試以下
第一篇鏈接
第二篇鏈接
第三篇
@Injectable() export class CustomHttp extends Http { constructor(backend: ConnectionBackend, defaultOptions: RequestOptions) { super(backend, defaultOptions); } request(url: string | Request, options?: RequestOptionsArgs): Observable{ console.log("request..."); return super.request(url, options).catch(res => { // do something }); } get(url: string, options?: RequestOptionsArgs): Observable { console.log("get..."); return super.get(url, options).catch(res => { // do something }); } }
app.module.ts里寫法過時了
bootstrap(AppComponent, [HTTP_PROVIDERS, new Provider(Http, { useFactory: (backend: XHRBackend, defaultOptions: RequestOptions) => new CustomHttp(backend, defaultOptions), deps: [XHRBackend, RequestOptions] }) ]);
按照上述代碼,寫法與angular2 r6不同,不知道怎么改。繼續(xù)搜索,發(fā)現(xiàn)大部分寫法都雷同,只是注入方式不同,后面看到了r6的注入方式,折騰幾次,有了結(jié)果
自己的Interceptcustomhttp.ts
import { Injectable } from "@angular/core"; import { Http, Request, RequestOptionsArgs, Response, RequestOptions, ConnectionBackend, Headers } from "@angular/http"; import "rxjs/Rx"; import { Observable } from "rxjs/Observable"; import { PubSubService } from "./shared/pubsub.service"; @Injectable() export class CustomHttp extends Http { _pubsub: PubSubService; constructor(backend: ConnectionBackend, defaultOptions: RequestOptions, pubsub: PubSubService) { super(backend, defaultOptions); this._pubsub = pubsub; } request(url: string | Request, options ? : RequestOptionsArgs): Observable < Response > { console.log("good"); return this.intercept(super.request(url, options)); } get(url: string, options ? : RequestOptionsArgs): Observable < Response > { return this.intercept(super.get(url, options)); } post(url: string, body: string, options ? : RequestOptionsArgs): Observable < Response > { return this.intercept(super.post(url, body, this.getRequestOptionArgs(options))); } put(url: string, body: string, options ? : RequestOptionsArgs): Observable < Response > { return this.intercept(super.put(url, body, this.getRequestOptionArgs(options))); } delete(url: string, options ? : RequestOptionsArgs): Observable < Response > { return this.intercept(super.put(url, this.getRequestOptionArgs(options))); } 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"); return options; } intercept(observable: Observable < Response > ): Observable < Response > { this._pubsub.beforeRequest.emit("beforeRequestEvent") observable.subscribe(null, (err) => { console.log("err"); this._pubsub.afterRequest.emit("afterRequestEvent"); this.handleError(err.status); }, () => { console.log("complete"); this._pubsub.afterRequest.emit("afterRequestEvent"); }); return observable; } handleError(status) { if (status === 0) { this._pubsub.errorToast.emit("請求響應(yīng)錯誤,請檢查網(wǎng)絡(luò)"); } else if (status === 404) { this._pubsub.errorToast.emit("請求鏈接不存在,請聯(lián)系管理員"); } else if (status === 500) { this._pubsub.errorToast.emit("服務(wù)器出錯,請稍后再試"); } else { this._pubsub.errorToast.emit("未知錯誤,請檢查網(wǎng)絡(luò)"); } } }
pubsup.service.ts
import { Injectable } from "@angular/core"; import { Subject } from "rxjs/Subject"; // 發(fā)布訂閱事件, 繼承自Subject, emit用于發(fā)射事件 class PubSubEvent extends Subject < String > { constructor() { super(); } emit(value) { super.next(value); } } @Injectable() export class PubSubService { beforeRequest: PubSubEvent; afterRequest: PubSubEvent; errorToast: PubSubEvent; successToast: PubSubEvent; showPupup: PubSubEvent; hidePupup: PubSubEvent; confirm: PubSubEvent; constructor() { this.beforeRequest = new PubSubEvent(); this.afterRequest = new PubSubEvent(); this.errorToast = new PubSubEvent(); this.successToast = new PubSubEvent(); this.showPupup = new PubSubEvent(); this.hidePupup = new PubSubEvent(); this.confirm = new PubSubEvent(); } }
app.module.ts
import { NgModule, Injectable } from "@angular/core"; import { BrowserModule } from "@angular/platform-browser"; import { FormsModule } from "@angular/forms"; import { HttpModule, Http, XHRBackend, RequestOptions } from "@angular/http"; // import { InMemoryWebApiModule } from "angular-in-memory-web-api"; import { HeroData } from "./hero/hero-data"; import { routing } from "./app.routing"; import { AppComponent } from "./app.component"; import { CrisisCenterComponent } from "./crisis/crisis-center.component"; import { MapComponent } from "./map/map.component"; import { CustomHttp } from "./customhttp"; import { MapService } from "./map/map.service"; import { PubSubService } from "./shared/pubsub.service"; import { PubSubComponent } from "./shared/pubsub.component"; @NgModule({ declarations: [ AppComponent, CrisisCenterComponent, MapComponent, PubSubComponent ], imports: [ BrowserModule, FormsModule, HttpModule, // InMemoryWebApiModule.forRoot(HeroData), routing ], providers: [ MapService, PubSubService, { provide: Http, useFactory: (backend: XHRBackend, defaultOptions: RequestOptions, pubsub: PubSubService) => new CustomHttp(backend, defaultOptions, pubsub), deps: [XHRBackend, RequestOptions, PubSubService] } ], bootstrap: [AppComponent], }) export class AppModule {}
最后是pubsup.component.ts,我是將loading, toast, pupup放在了一起
loading將在每個請求前顯示,請求失敗或結(jié)束隱藏
toast將在請求失敗顯示2秒鐘,或者在其他組件里調(diào)用
pupup將在刪除事件前提問,想放在delete api里自動顯示并處理,但是沒有實現(xiàn)
具體代碼在我github:https://github.com/jiangbo201...
import { Component, Input } from "@angular/core"; import { Http } from "@angular/http"; import { PubSubService } from "./pubsub.service"; @Component({ selector: "app-pubsub", templateUrl: "./pubsub.component.html", styleUrls: ["./pubsub.component.css"] }) export class PubSubComponent { showloading = false; showPupub = false; showSuccessToast = false; showErrorToast = false; errorValue: any = "error"; successValue: any = "success"; _pubsub: PubSubService; constructor(public http: Http, public pubsub: PubSubService) { this._pubsub = pubsub; } cancel() { this.showPupub = false; } confirm() { this.showPupub = false; this._pubsub.confirm.emit("confirm"); } ngOnInit() { this._pubsub.beforeRequest.subscribe(data => { console.log(data); this.showloading = true; }); this._pubsub.afterRequest.subscribe(data => { console.log(data); this.showloading = false; }); this._pubsub.errorToast.subscribe(data => { console.log(data); this.showErrorToast = true; this.errorValue = data; let that = this; // setTimeout(function() { // console.log(this); // that.showErrorToast = false; // }, 2000); }); this._pubsub.successToast.subscribe(data => { console.log(data); this.showSuccessToast = true; this.successValue = data; let that = this; setTimeout(function() { that.showSuccessToast = false; }, 2000); }); this._pubsub.showPupup.subscribe(data => { this.showPupub = true; console.log(data); }); this._pubsub.hidePupup.subscribe(data => { console.log(data); this.showPupub = false; }); } }
最后,我想在每個刪除aip里自動攔截,并彈出提示,如果確定刪除就執(zhí)行,如果放棄就return
但是不知道怎么阻塞執(zhí)行,歡迎交流
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://specialneedsforspecialkids.com/yun/80661.html
摘要:回顧上一次參加還是年。年的還是真正的,年的會議早已經(jīng)把英文全稱去掉,改稱全球大前端技術(shù)大會。同時與產(chǎn)品協(xié)作從產(chǎn)品設(shè)計方面突出關(guān)注點,做產(chǎn)品設(shè)計方面的優(yōu)化,如站新版改造減少頁面元素,將播放器窗口直接顯示在第一屏。 回顧 上一次參加 GMTC 還是 2017 年。那時的我還是剛剛參加工作并在試用期辭職的菜鳥。 2017 年的 GMTC 還是真正的 Global Mobile Tech Co...
平日學習接觸過的網(wǎng)站積累,以每月的形式發(fā)布。2017年以前看這個網(wǎng)址:http://www.kancloud.cn/jsfron... 1. Javascript 前端生成好看的二維碼 十大經(jīng)典排序算法(帶動圖演示) 為什么知乎前端圈普遍認為H5游戲和H5展示的JSer 個人整理和封裝的YU.js庫|中文詳細注釋|供新手學習使用 擴展JavaScript語法記錄 - 掉坑初期工具 漢字拼音轉(zhuǎn)換...
平日學習接觸過的網(wǎng)站積累,以每月的形式發(fā)布。2017年以前看這個網(wǎng)址:http://www.kancloud.cn/jsfron... 1. Javascript 前端生成好看的二維碼 十大經(jīng)典排序算法(帶動圖演示) 為什么知乎前端圈普遍認為H5游戲和H5展示的JSer 個人整理和封裝的YU.js庫|中文詳細注釋|供新手學習使用 擴展JavaScript語法記錄 - 掉坑初期工具 漢字拼音轉(zhuǎn)換...
平日學習接觸過的網(wǎng)站積累,以每月的形式發(fā)布。2017年以前看這個網(wǎng)址:http://www.kancloud.cn/jsfron... 1. Javascript 前端生成好看的二維碼 十大經(jīng)典排序算法(帶動圖演示) 為什么知乎前端圈普遍認為H5游戲和H5展示的JSer 個人整理和封裝的YU.js庫|中文詳細注釋|供新手學習使用 擴展JavaScript語法記錄 - 掉坑初期工具 漢字拼音轉(zhuǎn)換...
平日學習接觸過的網(wǎng)站積累,以每月的形式發(fā)布。2017年以前看這個網(wǎng)址:http://www.kancloud.cn/jsfron... 1. Javascript 前端生成好看的二維碼 十大經(jīng)典排序算法(帶動圖演示) 為什么知乎前端圈普遍認為H5游戲和H5展示的JSer 個人整理和封裝的YU.js庫|中文詳細注釋|供新手學習使用 擴展JavaScript語法記錄 - 掉坑初期工具 漢字拼音轉(zhuǎn)換...
閱讀 2044·2021-11-15 11:39
閱讀 3226·2021-10-09 09:41
閱讀 1490·2019-08-30 14:20
閱讀 3262·2019-08-30 13:53
閱讀 3324·2019-08-29 16:32
閱讀 3362·2019-08-29 11:20
閱讀 3018·2019-08-26 13:53
閱讀 775·2019-08-26 12:18