使用Angular中的service服务来请求接口

294 阅读1分钟

创建服务的命令:

1669628716682.png

接口请求方式及返回的接口格式如下图: image.png

image.png

my-service.service.ts

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpParams, HttpClient } from '@angular/common/http';
import { map } from 'rxjs/internal/operators';

export interface SongSheet {

  stackerId: string,
  stackerNo: string,
  cameraNo: string,
  inner_rtsp_url: string,
  outer_rtsp_url: string,
  installdate: string,
  terminalId: number,
  terminalNo: string,
  terminalName: string
}

// 歌单列表
export interface SheetList {
  playlists: SongSheet[];
}


@Injectable({
  providedIn: 'root'
})
export class MyServiceService {

  constructor(private http: HttpClient) { }

  // 获取歌单列表
  getSheets(): Observable<SheetList> {
    const params = new HttpParams().set('StackerId', 'ed78a2581bf8406ab8d706bd11782627');
    return this.http.get('/stacker/findStackerAllCameras', { params }).pipe(map(res => res['data']));
  }


}

test.component.js

import { Component, OnInit } from '@angular/core';
import { MyServiceService } from '../../shared/service/my-service.service';

export interface SongSheet {

  stackerId: string,
  stackerNo: string,
  cameraNo: string,
  inner_rtsp_url: string,
  outer_rtsp_url: string,
  installdate: string,
  terminalId: number,
  terminalNo: string,
  terminalName: string
}

// 歌单列表
export interface SheetList {
  playlists: SongSheet[];
}

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styles: []
})
export class TestComponent implements OnInit {
  sheets: SheetList;
  constructor(private myServe: MyServiceService,) { }

  ngOnInit() {
    this.getList();
  }

  private getList() {
    this.myServe.getSheets().subscribe(sheets => {
      console.log('sheets', sheets);
      this.sheets = sheets;
    });
  }

}

最终返回的值如下: image.png