Angular实战记录---HTTP

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/WRian_Ban/article/details/84583483

简易版HTTP服务

xxx.service.ts结构如下:

import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
import { catchError, map, tap } from 'rxjs/operators';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';

const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};

@Injectable({
  providedIn: 'root',
})

export class EvaluationService {
    private EvaluationUrl = 'http://xxx.xxx.xxx.xxx:8001'; //服务器IP:端口号
    ···
    _updatePIData (reportId: any, trafficId: any, trafficPIData: any): Observable<any> {
		// 设置请求参数
	    const params = new HttpParams()
	    .set('reportId', reportId)
	    .set('interfaceId', trafficId)
	    .set('tcs', JSON.stringify(trafficPIData)); // 数组转化为json再传
	    // 设置API
	    const url = `${this.EvaluationUrl}/updateTcsData/`;
	    
	    return this.http.post<any>(url, httpOptions, {
		       params
		     }).pipe(
		       tap(data => this._log(`updatePIData`)),
		       catchError(this._handleError<any>('updatePIData'))
		    );
	    }

		//工具函数,log打印,捕捉错误
	      private _log(message: string) {
		    console.log(message);
		  }
		  private _handleError<T> (operation = 'operation', result?: T) {
		    return (error: any): Observable<T> => {
		      console.error(error); // log to console instead
		      this._log(`${operation} failed: ${error.message}`);
		      return of(result as T);
		    };
		  }
}

使用静态数据

  • 创建文件interface.ts,导出静态数据,有多少,导多少。

    export const REPORTS = {
      status: 200,
      result: [{
        date: '20181106',
        reportId: '561839db-e6ac-4a97-a942-0bb47990aae8',
        reportName: 'report3',
        activate: 'true'
      }, {
        date: '20181107',
        reportId: 'f7ab58b6-5251-45bd-9294-71451840b253',
        reportName: 'report8',
        activate: 'false'
      }]
    };
    ···
    export const REPORTDETAIL = {
      status: 200,
      result: {
        reportId: '561839db-e6ac-4a97-a942-0bb47990aae8',
        date: '20181118',
        reportName: 'report3',
      ···
    };
    
  • 在xxx.service.ts中导入

    import { Observable, of } from 'rxjs';
    ···
    import { REPORTS, REPORTDETAIL, ···} from '../interface';
    
      _updatePIData (reportId: any, trafficId: any, trafficPIData: any): Observable<any> {
        const params = new HttpParams()
        .set('reportId', reportId)
        .set('interfaceId', trafficId)
        .set('tcs', JSON.stringify(trafficPIData));
        const url = `${this.EvaluationUrl}/updateTcsData/`;
        
        return of ({
          status: 200,
          result: REPORTS
        });
        
      }
    

在组件中调用服务并接收请求结果

组件.component.ts中导入服务模块,并注册

···
import { EvaluationService } from '../../evaluation.service';
···
export class PerFormanceIndicatorComponent implements OnInit{

constructor(
  private _AI_E_Serve: EvaluationService,
  ···
  ) { }
  ···
 someFunc(): void {
    this._AI_E_Serve. _updatePIData(this.reportId, this.trafficId, this.tempPerformanceTableData)
    .subscribe(data => {
      if (data.status === 200) {
        ···
      } else {
        this.message.info('save failed.');
      }
    });
  }

猜你喜欢

转载自blog.csdn.net/WRian_Ban/article/details/84583483