Параметры запроса Angular HTTP-запроса: методы и примеры

В Angular существует несколько способов включения параметров запроса в HTTP-запрос. Вот некоторые часто используемые подходы:

  1. Использование свойства paramsкласса HttpParams:

    import { HttpClient, HttpParams } from '@angular/common/http';
    // Create an instance of HttpParams
    let params = new HttpParams();
    // Set the desired query parameters
    params = params.set('param1', 'value1');
    params = params.set('param2', 'value2');
    // Pass the params object as an options parameter in the request
    this.http.get('https://example.com/api', { params }).subscribe(response => {
     // Handle the response
    });
  2. Добавление параметров запроса к URL-адресу запроса:

    import { HttpClient } from '@angular/common/http';
    // Construct the URL with query parameters
    const url = 'https://example.com/api?param1=value1&param2=value2';
    // Send the GET request
    this.http.get(url).subscribe(response => {
     // Handle the response
    });
  3. Использование объекта HttpParamsс методом fromObject:

    import { HttpClient, HttpParams } from '@angular/common/http';
    // Create an instance of HttpParams from an object
    const params = new HttpParams({ fromObject: { param1: 'value1', param2: 'value2' } });
    // Pass the params object as options in the request
    this.http.get('https://example.com/api', { params }).subscribe(response => {
     // Handle the response
    });
  4. Создание параметров запроса вручную:

    import { HttpClient } from '@angular/common/http';
    // Construct the query string manually
    const queryString = 'param1=value1&param2=value2';
    // Construct the URL with the query string
    const url = `https://example.com/api?${queryString}`;
    // Send the GET request
    this.http.get(url).subscribe(response => {
     // Handle the response
    });