Angular:使用service进行http请求的简单封装

①使用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);
      });
  }
}

猜你喜欢

转载自www.cnblogs.com/xinhej/p/13378554.html