Angular:使用service進行http請求的簡單封裝


①使用ng g service services/storage創建一個服務組件

②在app.module.ts 中引入HttpClientModule模塊

③在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);
      });
  }
}

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM