微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

angular5.x拦截器 给get post请求添加参数user_token

export class Interceptor implements HttpInterceptor {
public myAppListService;
constructor(private message: NzMessageService,private injector: Injector) {
}

public intercept(req: HttpRequest<any>,next: HttpHandler): Observable<HttpEvent<any>> {
this.myAppListService = this.injector.get(MyAppListService);
this.myAppListService.selectedUserToken = getQueryString(‘user_token‘) || sessionStorage.getItem(‘user_token‘);
 
if (this.myAppListService.selectedUserToken !== ‘null‘) {
let newParams;
let newBody;
if (req.method === ‘GET‘) {
let userToken = this.myAppListService.selectedUserToken;
if (userToken) {
newParams = req.params.set(‘user_token‘,userToken);
const comreq = req.clone({
params: newParams,
body: newBody
});
return next.handle(comreq).do((res) => {
this.handleResponse(res);
});
}
} else if (req.method === ‘POST‘ && req.headers.get(‘content-type‘).indexOf(‘application/x-www-form-urlencoded;‘) > -1) {
// if (req.body.indexOf(‘user_token=‘)) {
let userToken = this.myAppListService.selectedUserToken;
if (userToken) {
if (req.body.match(/(^|&)user_token=([^&]*)(&|$)/)) {
newBody = req.body.replace(req.body.match(/(^|&)user_token=([^&]*)(&|$)/)[0],‘‘);
newBody = newBody + ‘&user_token=‘ + userToken;
} else {
newBody = ‘&user_token=‘ + userToken;
}
const comreq = req.clone({
params: newParams,
body: newBody
});
return next.handle(comreq).do((res) => {
this.handleResponse(res);
});
}
// }
}

}
const comreq = req.clone();
return next.handle(comreq).do((res) => {
this.handleResponse(res);
});
}
public handleResponse(res) {
if (res instanceof HttpResponse) {
const data = res.body;
if (data.status && data.status === 2) {
this.message.error(data.data);
location.href = ‘/index.PHP?r=Login/Ulogin‘;
}
if (data.status && data.status === 1 && data.data === ‘应用不存在,或者您不是应用管理者‘) {
location.href = ‘/index.PHP?r=Login/Ulogin‘;
return;
}
}
}
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐