1. 首先,在 Angular 的模块中导入 HttpClientModule:
import { HttpClientModule } from '@angular/common/http';
  1. 在需要使用服务的组件中导入 HttpClient:
import { HttpClient } from '@angular/common/http';
  1. 在服务中创建一个方法,使用 HttpClient 发送 GET 请求:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class TestService {
  private apiUrl = '/test';

  constructor(private http: HttpClient) { }

  getTest(myId: number) {
    const params = { myId: myId.toString() };
    return this.http.get(this.apiUrl, { params });
  }
}
  1. 在组件中使用服务:
import { Component } from '@angular/core';
import { TestService } from './test.service';

@Component({
  selector: 'app-test',
  template: `<button (click)="getTest()">GET Test</button>`
})
export class TestComponent {
  constructor(private testService: TestService) { }

  getTest() {
    const myId = 1;
    this.testService.getTest(myId).subscribe((data) => {
      console.log(data);
    });
  }
}

这样就可以在组件中点击按钮,调用服务中的 getTest 方法发送 GET 请求,参数为 myId=1。服务返回的数据可以在组件中进行处理

angular 写一个GET请求 test 的服务参数是myId=1

原文地址: https://www.cveoy.top/t/topic/ceCO 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录