以前一直没有想过写一些东西来把项目中用到的知识点及技术实现做一个归纳整理并分享出来。现在打算逐渐的把项目中的一些东西整理并分享出来,与大家共勉!

angular本身自带访问组件http和httpclient,组件本身都是异步模式访问。本文只列举了对http组件的封装同时也一同处理会话超时监控。

实现思路概述:

1、将请求入参和出参统一约定

2、封装方法将请求参数、数据处理方法、数据呈现方法、访问错误处理方法封装在一起,业务调用通过服务调用该封装方法,
同时把请求参数、数据处理方法、数据呈现方法、访问错误处理方法传过来即可

3、在每次请求交互时,都会记录当前请求时间。系统工作台组件中增加监控处理,判断是否超时,超时分钟可自定义

下面是相关实现代码:

1、封装方法

import { NgModule } from '@angular/core';
import { Injectable } from '@angular/core';
import { HttpModule, Headers, Http, Response, Request, RequestOptionsArgs, ResponseOptionsArgs, RequestOptions } from '@angular/http';
import { trigger, state, style, transition, animate, keyframes } from '@angular/animations';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';

//使用三方js库
declare var CryptoJS:any;

@Injectable()
export class CommonRootService {

constructor(private http: Http) { }

//AES加密
public encrypt(word: string, key: string, iv: string): string {
let keys = CryptoJS.enc.Utf8.parse(key);
let ivs = CryptoJS.enc.Utf8.parse(iv);
let srcs = CryptoJS.enc.Utf8.parse(word);
let encrypted = CryptoJS.AES.encrypt(srcs, keys, { iv: ivs, mode: CryptoJS.mode.CBC });
return encrypted.toString();
}

public decrypt(word: string, key: string, iv: string) {
let keys = CryptoJS.enc.Utf8.parse(key);
let ivs = CryptoJS.enc.Utf8.parse(iv);
let decrypt = CryptoJS.AES.decrypt(word, keys, { iv: ivs, mode: CryptoJS.mode.CBC });
return CryptoJS.enc.Utf8.stringify(decrypt).toString();
}

public delayTimeMS(msseconds: number = 0): void {
for (let t = Date.now(); Date.now() - t <= msseconds;);
}

//Manage onlineTime,记录当前在线时间
public sessionMgt_onlineTime(currrOnLineTime: string, actionflag: string): any {
var resobjs: any;
if (actionflag == "R") {
if (localStorage.getItem("sessiononlineTime") != null && localStorage.getItem("sessiononlineTime").toString() != "") {
resobjs = localStorage.getItem("sessiononlineTime");
}
}
else if (actionflag == "S") {
localStorage.setItem("sessiononlineTime", currrOnLineTime);
}
else if (actionflag == "D") {
localStorage.removeItem('sessiononlineTime');
}
return resobjs;
}

//整体封装localStorage session管理
public sessionMgt(sessionName:string, sessionValue: string, actionflag: string): any {
let resobjs: any;
let sessionNames:string = "session" + sessionName;
if (actionflag == "R") {
if (localStorage.getItem(sessionNames) != null && localStorage.getItem(sessionNames).toString() != "") {
resobjs = localStorage.getItem(sessionNames);
}
}
else if (actionflag == "S") {
localStorage.setItem(sessionNames, sessionValue);
}
else if (actionflag == "D") {
localStorage.removeItem(sessionNames);
}
return resobjs;
}

//http encapsulation
public getHttpInfoData(reqdata: RequestParams, resdataFunc: any, displayresdataFunc: any, errorFunc: any): void {
if (reqdata.Reqmethod == "") {
reqdata.Reqmethod = "get";
}
if (reqdata.ReqdataType == "") {
reqdata.ReqdataType = "application/json";
}
let dataTypeStr = 'json';
let currReqAddr: string = this.getCurrServAddr(reqdata);
let selecttoken: string = this.sessionMgt("getToken", "", "R"); //读取令牌

this.sessionMgt_onlineTime(new Date().toJSON(), "S"); //设置当前交互时间

//let headers = new Headers({ 'Content-Type': reqdata.ReqdataType, dataType: dataTypeStr, 'Authorization': 'Basic ' + btoa("" + ":" + selecttoken) });
let headers = new Headers({ 'Content-Type': reqdata.ReqdataType, 'token': selecttoken });
let options = new RequestOptions({ headers: headers });

let bizparams: any = { 'req': JSON.stringify(reqdata) };

if (reqdata.Reqmethod == "post") {
this.http.post(currReqAddr, bizparams, options)
.map(resdataFunc)
.catch(err => this.getHandlerError(err, errorFunc))
.subscribe(displayresdataFunc)
}
else {
this.http.get(currReqAddr, options)
.map(resdataFunc)
.catch(err => this.getHandlerError(err, errorFunc))
.subscribe(displayresdataFunc)
}
}
//http encapsulation with token
public getHttpInfoDataAuth(reqdata: RequestParams, resdataFunc: any, displayresdataFunc: any, errorFunc: any): void {
if (reqdata.Reqmethod == "") {
reqdata.Reqmethod = "get";
}
if (reqdata.ReqdataType == "") {
reqdata.ReqdataType = "application/json";
}
let dataTypeStr = 'json';
let currReqAddr: string = this.getCurrServAddr(reqdata);
let selecttoken: string = this.sessionMgt("getToken", "", "R"); //读取令牌

this.sessionMgt_onlineTime(new Date().toJSON(), "S"); //设置当前交互时间

//let headers = new Headers({ 'Content-Type': reqdata.ReqdataType, dataType: dataTypeStr, 'Authorization': 'Basic ' + btoa("" + ":" + selecttoken) });
let headers = new Headers({ 'Content-Type': reqdata.ReqdataType, 'token': selecttoken });
let options = new RequestOptions({ headers: headers });

let bizparams: any = { 'req': JSON.stringify(reqdata) };

if (reqdata.Reqmethod == "post") {
this.http.post(currReqAddr, bizparams, options)
.map(resdataFunc)
.catch(err => this.getHandlerError(err, errorFunc))
.subscribe(displayresdataFunc)
}
else {
this.http.get(currReqAddr, options)
.map(resdataFunc)
.catch(err => this.getHandlerError(err, errorFunc))
.subscribe(displayresdataFunc)
}
}

public getHandlerError(error: Response | any, userErrFunc: any) {
let errMsg: string;
if (error instanceof Response) {
let body = error.json() || '';
let err = body.error || JSON.stringify(body);
errMsg = err;
} else {
errMsg = error.message ? error.message : error.toString();
}
userErrFunc(errMsg);
return Observable.throw(errMsg);
}

//http encapsulation webapi请求
public getHttpInfoDataWebapi(reqdata: Reqobj, resdataFunc: any, displayresdataFunc: any, errorFunc: any): void {
if (reqdata.reqmethod == "") {
reqdata.reqmethod = "get";
}
if (reqdata.reqdatatype == "") {
reqdata.reqdatatype = "application/json; charset=utf-8"; 
//reqdata.reqdatatype = "application/x-www-form-urlencoded;charset=UTF-8";
}
let dataTypeStr = 'json';

let selecttoken: string = this.sessionMgt("getToken", "", "R"); //读取令牌
this.sessionMgt_onlineTime(new Date().toJSON(), "S"); //设置当前交互时间

let headers = new Headers();
headers.append('Content-Type', reqdata.reqdatatype); 
let options = new RequestOptions({ headers: headers});

if (reqdata.reqmethod == "post") {
this.http.post(reqdata.dataUrl, reqdata, options)
.map(resdataFunc)
.catch(err => this.getHandlerError(err, errorFunc))
.subscribe(displayresdataFunc)
}
else {
this.http.get(reqdata.dataUrl, options)
.map(resdataFunc)
.catch(err => this.getHandlerError(err, errorFunc))
.subscribe(displayresdataFunc)
}
}

//获取当前服务
public getCurrentServ(serviden: string, versioniden: string, servtype: string, servconfig: any): any {
let reqServ = {}; //返回当前服务 
if (servconfig != "" && servconfig != undefined) {
let servconfigArrr: any = JSON.parse(servconfig);
if (servconfigArrr.length > 0) {
for (let i = 0; i < servconfigArrr.length; i++) {
if (servconfigArrr[i]["serviden"] == serviden && servconfigArrr[i]["version"] == versioniden) {
reqServ = servconfigArrr[i];
break;
}
}
}
}

return reqServ;
}

//获取当前请求地址
//reqdata.Addrtype参数值为nodecenter(节点中心地址)、xxx(业务节点地址)、terminal(终端网页地址)
public getCurrServAddr(reqdata: RequestParams): string {
let resServAddr: string = "";
let servconfigmgt: any = this.getCurrentServ(reqdata.ServIdentifer, reqdata.ServVersionIden, reqdata.ServVersionIden, this.getUseServices());
if (servconfigmgt) {
if (servconfigmgt.url_addr != "" && servconfigmgt.url_addr != undefined) {
resServAddr = servconfigmgt.url_addr + "/" + servconfigmgt.servcodename + reqdata.GetDataUrl;
}
else {
if (reqdata.AddrType == "nodecenter") {
//TODO 预留自动监控节点中心状态,变更可用节点中心地址
let nodecenterobj: any = JSON.parse(this.sessionMgt("getNodeCenterAddr", "", "R"));
let nodecenteraddress: string = "";
if (nodecenterobj.master_node_state == "1") {
nodecenteraddress = nodecenterobj.master_node;
}
else if (nodecenterobj.slave_node_state == "1") {
nodecenteraddress = nodecenterobj.slave_node;
}
resServAddr = nodecenteraddress + "/" + servconfigmgt.servcodename + reqdata.GetDataUrl;
//resServAddr = "/api/" + servconfigmgt.servcodename + reqdata.GetDataUrl; 

else if (reqdata.AddrType == "terminal") {
resServAddr = reqdata.GetDataUrl;
}
else if (reqdata.AddrType == "PlcService") {
resServAddr = reqdata.Reqtype + reqdata.GetDataUrl;
}
else {
//获取请求模块当前可用节点地址
let bizNodeList:any[] = JSON.parse(this.sessionMgt("getBizNodeAddr", "", "R"));
let moudineAdd:string = "";
for (let i = 0; i < bizNodeList.length; i++) {
if (bizNodeList[i].Moudiden == reqdata.AddrType) {
moudineAdd = bizNodeList[i].Url_addr;
break;
}
}
resServAddr = moudineAdd + "/" + servconfigmgt.servcodename + reqdata.GetDataUrl;
}
}
}

return resServAddr;
}

//计算时间差,resFlag表示时间差的类型 d 相差天数 h 相差小时数 m 相差分钟数 s 相差秒数, ms 相差秒数,其他后续再扩展 
public dateTimeSeg(startTimeStr: string, endTimeStr: string, resFlag: string): number {
let difValue: number = 0; //相差的数值

let startTime: Date = new Date(startTimeStr);
let endTime: Date = new Date(endTimeStr);

let startDateMS: number = startTime.getTime(); //到日期的毫秒数
let endDateMS: number = endTime.getTime(); //到日期的毫秒数
//相差总毫秒数
let tottleDiffMS: number = endDateMS - startDateMS;

if (resFlag == "d") {

difValue = Math.floor(tottleDiffMS / (24 * 3600 * 1000));

}
else if (resFlag == "h") {

difValue = Math.floor(tottleDiffMS / (3600 * 1000));

}
else if (resFlag == "m") {

difValue = Math.floor(tottleDiffMS / (60 * 1000));

}
else if (resFlag == "s") {

difValue = Math.floor(tottleDiffMS / (1000));

}
else if (resFlag == "ms") {

difValue = tottleDiffMS;

}

return difValue;

}

}

//Public structure definition

//request parameters encapsulation
export class RequestParams {
public GetDataUrl: string = "";
public Reqtype: string = "";
public Reqmethod: string = "";
public ReqdataType: string = "";
public Reqdata: string = "";
public Reqi18n: string = "";
public ServIdentifer: string = "";
public ServVersionIden: string = "";
//AddrType 参数值为nodecenter(节点中心地址)、biznode(业务节点地址)、terminal(终端网页地址)
public AddrType: string = "";
}

//response parameters encapsulation
export class ResponseParams {
public respflag: string = "";
public resptoolstr: string = "";
public respdata: string = "";
public pagertottlecounts: string = "";
}

//request parameters encapsulation webapi
export class Reqobj {
public dataUrl:string = "";
public reqtype: string = "";
public reqmethod: string = "";
public reqdatatype: string = "";
public sn: string = "";
public output: string = "";
public reqiden: string = "";
public reqdataiden: string = "";
public reqdatas: string = "";
public reqi18n: string = "";
public reqversion: string = "";

constructor(_dataUrl:string, _reqtype:string, _reqmethod:string, _reqdatatype:string,
_sn: string, _output: string, _reqdataiden: string, _reqdatas: string, _reqi18n: string,
_reqiden: string, _reqversion: string) {
this.dataUrl = _dataUrl;
this.reqtype = _reqtype;
this.reqmethod = _reqmethod;
this.reqdatatype = _reqdatatype;
this.sn = _sn;
this.output = _output;
this.reqdataiden = _reqdataiden;
this.reqdatas = _reqdatas;
this.reqi18n = _reqi18n; 
this.reqiden = _reqiden;
this.reqversion = _reqversion;
}
}
export class Reqdata {
public key: string = "";
public value: string = "";
}
export class response {
public status: string = "";
public datetime: string = "";
public respdatas: string = "";
public tottlerecords: string = "";
public resperrordatas: string = "";
}

//检查数据库参数
export class CheckBizObjectRepatParams {
public Bizobjectname: string = "";
public WherePropertyL: any[] = [];
public Splitchar: string = "";
}

2、监控超时

//超时处理函数,直接退出系统路由到退出提示组件

timeOutFunction(): void {

let nodecenterobj: any = JSON.parse(this.commonmodule.getNodeCenterAddr());

let currDate: Date = new Date(); //当前时间

let difvalue: number = this.commonmodule.dateTimeSeg(this.commonmodule.sessionMgt_onlineTime("", "R"), currDate.toJSON(), "m");

let tiemoutValue: number = parseInt(nodecenterobj.timeOutMinutes);

if (difvalue > tiemoutValue) {

if (this.quitFlag != "TimeOut") {

this.quitFlag = "TimeOut";

this.router.navigateByUrl("quitsystem"); 
}

}

}

3、调用样例

服务样例:

import { Injectable } from '@angular/core';
import { CommonRootService, MainValueName, PagingParam, RequestParams, ResponseParams } from '../common_module/common.service';

@Injectable()
export class SysmanagerService {
constructor(private commonmodule: CommonRootService) { }

//获取用户组名
getGroupName(reqdata: RequestParams, resdataFunc: any, displayresdataFunc: any, errorFunc: any): void {

this.commonmodule.getHttpInfoDataAuth(reqdata, resdataFunc, displayresdataFunc, errorFunc);

}

}//class end

调用样例:

//查询数据
querydata(): void {
this.getData(1);
}

getData(currpageindex: number): void {
this.condiv = true;

//this.pagingParam.PageSize = 5; //默认10
this.pagingParam.PageIndex = currpageindex;

let currqueryobj: any = {};
currqueryobj.GROUPID = this.groupname;
currqueryobj.ISUSE = this.isuse;

let groupreqobj = [{ queryItemKey: "SSY_PagingParam", queryItemValue: JSON.stringify(this.pagingParam) },
{ queryItemKey: "SSY_GROUP_DICT", queryItemValue: JSON.stringify(currqueryobj) }];

let reqdata: RequestParams = new RequestParams();
reqdata.AddrType = "FrameMgt";
reqdata.GetDataUrl = "/FrameApi/GetGroupPagerN";
reqdata.Reqmethod = "post";
reqdata.Reqdata = JSON.stringify(groupreqobj);
reqdata.ReqdataType = "";
reqdata.Reqtype = "getgroupdata";
reqdata.Reqi18n = this.commonmodule.getI18nlang();
reqdata.ServIdentifer = "frameManager";
reqdata.ServVersionIden = "1.0";

this.sysmanagerServ.getGroups(reqdata,
res => this.getDataResdataFunc(res), res => this.getDataDisplaydataFunc(res), err => this.getDataErrorFunc(err));
}

getDataResdataFunc(data: any): any {
return data;
}
getDataDisplaydataFunc(data: any): void {
this.condiv = false;
this.bindcurrdata = [];
this.tottlecounts = 0;
this.currdata = [];
this.olddata = [];
if (data.status == 200) {
let respdata: ResponseParams = JSON.parse(JSON.parse(data._body));
if (respdata.respflag == "1") {
let binddata: any = [];
binddata = JSON.parse(respdata.respdata);
for (var i = 0; i < binddata.length; i++) {
if (binddata[i]["ISUSE"] == "1") {
binddata[i]["ISUSE"] = true;
}
else {
binddata[i]["ISUSE"] = false;
}
}
this.currdata = this.commonmodule.copyArrayToNewArray(binddata);
this.olddata = this.commonmodule.copyArrayToNewArray(binddata);
this.tottlecounts = +respdata.pagertottlecounts;

this.bindcurrdata = [];
this.bindcurrdata = this.commonmodule.copyArrayToNewArray(binddata);
}
else {
this.errorinfos = [];
this.errorinfos.push({ severity: 'warn', summary: this.commonlang.noticeInfoTitle, detail: this.commonlang.noticeNoFoundData });
}
}
else {
this.errorinfos = [];
this.errorinfos.push({ severity: 'warn', summary: this.commonlang.noticeInfoTitle, detail: this.commonlang.noticeError });
}
}
getDataErrorFunc(err: string) {
this.errorinfos = [];
this.errorinfos.push({ severity: 'warn', summary: this.commonlang.noticeInfoTitle, detail: this.commonlang.noticeHttpError_info + err });
this.condiv = false;
}

获取实例源码请入QQ群706224870,在群文件中下载。

angular访问后台服务及监控会话超时的封装实现的更多相关文章

  1. angular访问后台服务及监控会话超时的封装

    angular访问后台服务及监控会话超时的封装 angular本身自带访问组件http和httpclient,组件本身都是异步模式访问.本文只列举了对http组件的封装同时也一同处理会话超时监控. 获 ...

  2. highchart访问一次后台服务返回多张图表数据

    本文承接上一篇,我们制作动态图表的时候,往往需要的不止一张图表,如果每张图表都与服务接口做一次交互的话未免太过频繁,这无论对前后还是后台都是一种压力,本文介绍一种一次访问返回多组数据的方式来减少前台与 ...

  3. cz.msebera.android.httpclient.conn.ConnectTimeoutException: Connect to /192.168.23.1:8080 timed out(Android访问后台一直说链接超时)

    明明之前还是可以运行的练习,过段时间却运行不了,一直说访问后台超时, 对于这个问题我整整弄了两天加一个晚上,心酸...,上网找了很多但是都解决不了,我就差没有砸电脑了. 首先 : 第一步:Androi ...

  4. node服务的监控预警系统架构

    需求背景 目前node端的服务逐渐成熟,在不少公司内部也开始承担业务处理或者视图渲染工作.不同于个人开发的简单服务器,企业级的node服务要求更为苛刻: 高稳定性.高可靠性.鲁棒性以及直观的监控和报警 ...

  5. vivo 服务端监控架构设计与实践

    一.业务背景 当今时代处在信息大爆发的时代,信息借助互联网的潮流在全球自由的流动,产生了各式各样的平台系统和软件系统,越来越多的业务也会导致系统的复杂性. 当核心业务出现了问题影响用户体验,开发人员没 ...

  6. Spring Boot(二十):使用spring-boot-admin对spring-boot服务进行监控

    Spring Boot(二十):使用spring-boot-admin对spring-boot服务进行监控 Spring Boot Actuator提供了对单个Spring Boot的监控,信息包含: ...

  7. Spring Boot (九): 微服务应用监控 Spring Boot Actuator 详解

    1. 引言 在当前的微服务架构方式下,我们会有很多的服务部署在不同的机器上,相互是通过服务调用的方式进行交互,一个完整的业务流程中间会经过很多个微服务的处理和传递,那么,如何能知道每个服务的健康状况就 ...

  8. istio: 无法提供内部访问外部服务

    现象 能够内部无法访问外部服务. 在部署测试服务 kubectl apply -f samples/sleep/sleep.yaml 设置环境变量 export SOURCE_POD=$(kubect ...

  9. vue学习过程总结(07) - vue的后台服务API封装及跨域问题的解决

    以登录流程为例说明接口的封装. 1.登录调用后台的登录api 登录界面的代码 <template> <div class="login-page"> < ...

随机推荐

  1. C#winform控件序列化,反序列化

    using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System. ...

  2. ansible roles实践 zookeeper集群部署

    1.下载解压 wget https://mirrors.tuna.tsinghua.edu.cn/apache/zookeeper/zookeeper-3.4.11/zookeeper-3.4.11. ...

  3. python os模块 文件操作

    Python内置的os模块可以通过调用操作系统提供的接口函数来对文件和目录进行操作 os模块的基本功能: >>> import os >>> os.name 'po ...

  4. python3 连接mysql数据库

    准备工作: 1.在本地虚拟机172.16.0.115上安装mysql,并设置权限如下 mysql> grant all privileges on *.* to root@"%&quo ...

  5. 使用Hot Chocolate和.NET 6构建GraphQL应用(2) —— 实体相关功能实现

    系列导航 使用Hot Chocolate和.NET 6构建GraphQL应用文章索引 需求 在本文中,我们将会准备好用于实现GraphQL接口所依赖的底层数据,为下一篇文章具体实现GraphQL接口做 ...

  6. URL Rewrite(四种重定向策略)

    目录 一:Rewrite基本概述 1.Rewrite简介 2.Rewrite基本概述 3.Rewrite作用 4.什么是URL? 二:rewrite语法 三:Rewrite标记Flag 1.last和 ...

  7. linux中wc命令

    目录 一:linux中wc命令 1.wc命令介绍 2.wc命令作用 3.wc命令格式 4.参数 5.解析案例 一:linux中wc命令 1.wc命令介绍 Linux wc命令用于计算字数. 利用wc指 ...

  8. Kubernetes之日志和监控(十五)

    一.日志和监控 1.1.Log 1.1.1.容器级别 通过docker命令查看容器级别的日志 docker ps --->containerid docker logs containerid ...

  9. CSS之创意hover效果

    一.发送效果 HTML <div id="send-btn"> <button> // 这里是一个svg的占位 Send </button> & ...

  10. 微信小程序之多选功能

    思路:把向得到的数组中添加一个布尔值,默认都为false,然后通过数组的映射功能把选中的布尔值,存储到数组中,在组件属性中,用三元运算符做判断即可 data:{ sampleArray: [{ id: ...