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

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,在群文件中下载。

转载于:https://www.cnblogs.com/maotou/p/angular.html

angular访问后台服务及监控会话超时的封装实现相关推荐

  1. JavaScript脚本访问后台服务实例

    js访问后台服务实例 前端代码: function GetHeatMapFunc() {         var s_time = "2017-11-12";         va ...

  2. 关于H5 开发app应用 移动端无法访问后台服务的总结

    H5 开发中,有很多隐藏的小问题,这些小问题,对于没有多少H5 app开发经验的来说,无疑会浪费大把时间,所以在此做个小结. 1,真机测试的时候,ajax请求一直返回error 原因分析: 1,请求成 ...

  3. 前后端完全分离出现跨域、无法访问后台解决方案

    系统为分布式,主体上分为三层,前端.服务消费端.服务提供端,前端代码记录后端服务器访问地址,由于后端服务不提供外网服务,故用户直接访问出现无法访问情况,但是前端服务器与后端服务器直接是互联互通的,所以 ...

  4. OpenShift 4 之Service Mesh教程(4)- 跟踪访问后端服务超时

    <OpenShift 4.x HOL教程汇总> 说明:本文已经在OpenShift 4.8环境中验证 本文说明如何在Istio中的VirtualService中设置访问的timeout特性 ...

  5. 后台服务被恶意脚本访问

    这几天写了后台API服务给前端调用,看命令行打印的log日志发现不断有请求调用我的后台服务,调用的RequestURI多为admin.php,mysqladmin.php,123.php.1234.p ...

  6. 「服务端」node服务的监控预警系统架构

    本文由尚妆前端开发工程师欲休撰写 本文发表于github尚妆博客,欢迎订阅! 需求背景 目前node端的服务逐渐成熟,在不少公司内部也开始承担业务处理或者视图渲染工作.不同于个人开发的简单服务器,企业 ...

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

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

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

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

  9. 后台服务架构高性能设计之道

    "N 高 N 可",高性能.高并发.高可用.高可靠.可扩展.可维护.可用性等是后台开发耳熟能详的词了,它们中有些词在大部分情况下表达相近意思.本序列文章旨在探讨和总结后台架构设计中 ...

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

    作者:vivo互联网服务器团队-Deng Haibo 一.业务背景 当今时代处在信息大爆发的时代,信息借助互联网的潮流在全球自由的流动,产生了各式各样的平台系统和软件系统,越来越多的业务也会导致系统的 ...

最新文章

  1. 彻底解决tensorflow:ImportError: Could not find 'cudart64_90.dll' tensorflow安装
  2. NLP(自然语言处理)详细笔记
  3. 机器学习线性回归算法实验报告_从零实现机器学习算法(九)线性回归
  4. P1160-队列安排【链表】
  5. 【前端性能优化】不用 setTimeout 实现防抖
  6. Esp8266物联网开发板详细使用教程
  7. PHP网站开启gzip压缩,PHP网站程序中开启Gzip压缩的两种方法
  8. Java泛型原理、类型擦除
  9. 【python教程入门学习】利用Python自动生成暴力破解的字典
  10. C++大小端转换程序
  11. 手工制作夜光星星的方法
  12. 华为谷歌安装器 Android6.0,gms安装器华为
  13. linux icmp 时间戳过滤,ICMP-linux c 时间戳请求功能实现
  14. java数据结构与算法总结(二十四)--RoaringBitmap数据结构及原理
  15. 解决微信公众号分享出去的是链接
  16. 不对等的爱情并不长久
  17. 一键启动oracle服务脚本,Oracle服务一键启动/关闭
  18. 第二证券|钠电池三种技术路线谁更将率先取代锂电池?
  19. 阿里妈妈技术团队5篇论文入选 KDD 2022
  20. WPF基础五:UI②内容元素Frame

热门文章

  1. [4/10]指定结进程名称的命令taskkill.exe
  2. 云服务器真假辨别奥秘
  3. AR技术介绍(Located in Android)
  4. 成都Uber优步司机奖励政策(1月16日)
  5. RMDB与hadoop的实时整合
  6. 斐波那契数列:一道100年后羊圈羊的数量算法题
  7. 请问mysql优化相关
  8. Nginx 场景应用
  9. 更改Mysql 密码的4种方法(转)
  10. redhat初始化yum源,使用阿里云yum源