import { HttpClient, HttpErrorResponse } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable, throwError } from 'rxjs'; import { catchError, retry } from 'rxjs/operators'; @Injectable({ providedIn: 'root' }) export class BuildingBasicInfosService { constructor( public http: HttpClient ) { } /** * 单位信息的api [获取/保存] */ readonly api_buildingInfo = 'api/Services/3D/BuildingBasicInfo'; /** * 事态标绘(电子沙盘)的api [获取/保存] */ readonly api_sandBox = "api/Services/3D/Sandboxie"; /** * 获取三维信息 */ getBuildingBasicInfos(name: string): Observable { return this.getInfos(this.api_buildingInfo, name); } /** * 保存三维信息 * @param name * @param data */ postBuildingBasicInfos(name: string, gasstationId: number, data: object): Observable { return this.postInfos(this.api_buildingInfo, data, { name: name, gasstationId: gasstationId }); } /** * 获取事态标绘的信息 * @param name */ getMarkData(name: string): Observable { return this.getInfos(this.api_sandBox, name); } /** * 推送事态标绘的信息 * @param name * @param data */ postMarkData(name: string, data: object): Observable { return this.postInfos(this.api_sandBox, data, { name: name }); } //#region 通用封装,新增api时调用即可,不需关心具体组装规则。若修改规则,只需修改此通用封装 /** * get类api所需的固定内容 */ readonly c_get = "/Get"; /** * post类api所需的固定内容 */ readonly c_post = "/PostOrPut"; /** * 通用消息头 */ readonly headers = { "Content-Type": "application/json" }; /** * 通用get 类api的封装 * @param api * @param name */ getInfos(api: string, name: string) { let id = { "name": name }; return this.http.get(api + this.c_get, { params: id }).pipe( catchError((err) => this.handleError(err)) ); } /** * 通用post 类api的封装 * @param api * @param name * @param data */ postInfos(api: string, body: object, params = {}) { let headers = this.headers; return this.http.post(api + this.c_post, `'${JSON.stringify(body)}'`, { headers, params }) .pipe( catchError((err) => this.handleError(err)) ); } //#endregion //#region 错误捕捉 private handleError(error: HttpErrorResponse) { if (error.error instanceof ErrorEvent) { // A client-side or network error occurred. Handle it accordingly. console.error('An error occurred:', error.error.message); } else { // The backend returned an unsuccessful response code. // The response body may contain clues as to what went wrong. if (error.status == 404) { console.log("404===" + error.error); } else { console.error( error + `Backend returned code ${error.status}, ` + `body was: ${error.error}`); } } // Return an observable with a user-facing error message. return throwError( error); } //#endregion }