Angular:使用service進行http請求的簡單封裝
阿新 • • 發佈:2020-07-26
①使用ng g service services/storage建立一個服務元件
②在app.module.ts 中引入建立的服務
③在services/http.service.ts中封裝一個簡單的http請求
import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; @Injectable({ providedIn: 'root' }) export class HttpService { public hxApi = 'http://127.0.0.1:3000/'; constructor(public http: HttpClient) { } get(api: any, obj: any): any {return new Promise((resolve, reject) => { //使用Promise進行二次封裝 this.http.get(this.hxApi + api, obj).subscribe({ next(res): any { resolve(res); }, error(err): any { reject(err); } }); }); } post(api: any, obj: any): any { const htttpOptions= { headers: new HttpHeaders({ 'Content-type': 'application/json' }) }; //post請求需要設定此引數 return new Promise((resolve, reject) => { this.http.post(this.hxApi + api, obj, htttpOptions).subscribe({ next(res): any { resolve(res); }, error(err): any { reject(err); } }); }); } }
④在元件中使用HttpService
import { Component } from '@angular/core'; import { HttpService } from './services/http.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.less'] }) export class AppComponent { title = 'angular-http'; constructor(public http: HttpService) { } getData(): void { this.http.get('users/xixi2', { params: { name: 'xixiGet' } }) //注意get請求和post請求的傳參方式不一樣 .then(res => { console.log(res); }) .catch(err => { console.log(err); }); } postData(): void { this.http.post('users/xixi', { name: 'xixiPost' }) .then(res => { console.log(res); }) .catch(err => { console.log(err); }); } }