創建common服務:
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; //首先安裝md5模塊 cnpm install ts-md5 --save import {Md5} from "ts-md5/dist/md5"; @Injectable({ providedIn: 'root' }) export class CommonService { public config: any = { baseUrl: 'http://127.0.0.1:8080/' } constructor(public http: HttpClient) { } /* api/focus */ ajaxGet(url:String) { var api = this.config.baseUrl + url; return new Promise((resove, reject) => { this.http.get(api).subscribe((response) => { resove(response); }, (error) => { reject(error); }) }) } /* api/focus */ ajaxPost(url:String, json:Object) { var api = this.config.baseUrl + url; return new Promise((resove, reject) => { this.http.post(api, json).subscribe((response) => { resove(response); }, (error) => { reject(error); }) }) } /* 生成簽名 var json={ uid:123, salt:'afsafdafadf' } */ sign(json){ var tempArr=[]; for(var attr in json){ tempArr.push(attr); } tempArr=tempArr.sort(); var tempStr=''; for(var j=0;j<tempArr.length;j++){ tempStr+=tempArr[j]+json[tempArr[j]] } // console.log(tempStr); return Md5.hashStr(tempStr); } }
在使用的頁面引入服務
import { CommonService } from '../services/common.service';
constructor(public common:CommonService) { }
請求接口:
var api="api/doLogin"; this.common.ajaxPost(api,{ username:this.userinfo.username, password:this.userinfo.password, }).then((response:any)=>{ console.log(response); if(response.success){ //1、成功后處理業務邏輯 }else{ alert(response.message); //toast } })