angular依赖注入 angular依赖注入

angular依赖注入

1.angular依赖注入

1.创建服务

2.在ngmodule内引入

3.使用

https://www.angular.cn/guide/architecture-services

2.http服务

  1. postFormData(endpoint: string, params?: any, reqOpts?: any){
  2. let par = {};//重新组合参数数组
  3. if (params) {
  4. for (let k in params) {
  5. if (typeof params[k] !== "undefined") {
  6. par[k] = params[k];
  7. }
  8. }
  9. }
  10. return this.http.post(this.url + endpoint,this.buildURLSearchParams(par),reqOpts);
  11. }

https://www.angular.cn/guide/http

3.RX的简单应用

  1. 拦截器
  1. import { Injectable } from '@angular/core';
  2. import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpResponse } from '@angular/common/http';
  3. import { Observable,throwError } from 'rxjs';
  4. import { mergeMap, catchError } from 'rxjs/operators';
  5. import { GlobalData, NativeService } from './index';
  6. import { TimeoutError } from 'rxjs';
  7. @Injectable()
  8. export class InterceptorService implements HttpInterceptor {
  9. constructor(public globalData: GlobalData,
  10. //private events: Events,
  11. public nativeService: NativeService) {}
  12. // intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
  13. intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
  14. const authReq = req.clone({
  15. url: (req.url),
  16. setHeaders: {
  17. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  18. Token: this.globalData.token?this.globalData.token:''
  19. }
  20. });
  21. if (authReq.method != 'GET') {
  22. this.showLoading();
  23. }
  24. return <any>next.handle(authReq).pipe(mergeMap((event: any) => {
  25. if (event instanceof HttpResponse && event.status !== 200) {
  26. return throwError(event);
  27. }
  28. // console.log(event);
  29. return Observable.create(observer => {
  30. if (event.body) {
  31. // console.log(event.body);
  32. // 统一判断全局状态返回
  33. if (event.body.status == -99) {
  34. this.nativeService.showToastTips(event.body.msg);
  35. window['epInstance']['emit']('toLogin', 0);
  36. } else if (event.body.status == -100) {
  37. // window['epInstance']['emit']('wechatLogin', event.body);
  38. }
  39. observer.next(event);
  40. } else {
  41. observer.next(event);
  42. }
  43. if (event.type > 0) {
  44. this.hideLoading();
  45. }
  46. }); // 请求成功返回响应
  47. }),
  48. catchError((res: HttpResponse<any>) => {
  49. // 请求失败处理
  50. this.hideLoading();
  51. if (!this.nativeService.isConnecting()) {
  52. this.nativeService.showToastTips('请连接网络');
  53. } else if (res instanceof TimeoutError) {
  54. this.nativeService.showToastTips('请求超时,请稍后再试!');
  55. } else {
  56. let msg = '请求发生异常';
  57. switch (res.status) {
  58. case 0:
  59. //console.log('未知的Api');
  60. msg = '未知的Api';
  61. break;
  62. case 401:
  63. break;
  64. case 404:
  65. //console.log('Api请求地址不存在');
  66. msg = 'Api请求地址不存在';
  67. //this.events.publish('toLogin');
  68. break;
  69. case 403:
  70. //console.log('业务错误');
  71. break;
  72. case 500:
  73. //console.log('服务器出错');
  74. msg = 'Api请求地址不存在';
  75. break;
  76. }
  77. this.nativeService.showToastTips(msg);
  78. }
  79. return throwError(event);
  80. }));
  81. }
  82. private count = 0; // 记录未完成的请求数量,当请求数为0关闭loading,当不为0显示loading
  83. private showLoading() {
  84. if (++this.count > 0) {// 一旦有请求就弹出loading
  85. this.globalData.showLoading && this.nativeService.showLoading();
  86. }
  87. }
  88. private hideLoading() {
  89. if (this.globalData.showLoading) {
  90. // 延迟处理可以避免嵌套请求关闭了第一个loading,突然后弹出第二个loading情况(结合nativeService.showLoading())
  91. setTimeout(() => {
  92. if (--this.count === 0) {// 当正在请求数为0,关闭loading
  93. this.nativeService.hideLoading();
  94. }
  95. }, 200);
  96. } else {
  97. this.globalData.showLoading = true;
  98. }
  99. }
  100. }

2.监听页面变化


https://www.angular.cn/guide/rx-library

评论 0

挤眼 亲亲 咆哮 开心 想想 可怜 糗大了 委屈 哈哈 小声点 右哼哼 左哼哼 疑问 坏笑 赚钱啦 悲伤 耍酷 勾引 厉害 握手 耶 嘻嘻 害羞 鼓掌 馋嘴 抓狂 抱抱 围观 威武 给力
提交评论

清空信息
关闭评论