MST

星途 面试题库

面试题:Angular中HTTP请求常用的请求方法及参数传递方式

在Angular中,列举至少三种常用的HTTP请求方法,并说明如何使用`HttpClient`模块针对不同请求方法进行参数传递,例如GET请求传递查询参数,POST请求传递请求体参数等。请给出简单代码示例。
17.0万 热度难度
前端开发Angular

知识考点

AI 面试

面试题答案

一键面试

常用HTTP请求方法

  1. GET:用于从服务器获取数据。
  2. POST:用于向服务器提交数据,通常用于创建新资源。
  3. PUT:用于更新服务器上的资源。
  4. DELETE:用于从服务器删除资源。

使用HttpClient模块传递参数示例

  1. GET请求传递查询参数
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor(private http: HttpClient) {}

  getData() {
    const params = {
      param1: 'value1',
      param2: 'value2'
    };
    this.http.get('http://example.com/api/data', { params }).subscribe(response => {
      console.log(response);
    });
  }
}
  1. POST请求传递请求体参数
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor(private http: HttpClient) {}

  postData() {
    const body = {
      key1: 'data1',
      key2: 'data2'
    };
    this.http.post('http://example.com/api/data', body).subscribe(response => {
      console.log(response);
    });
  }
}
  1. PUT请求传递请求体参数
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor(private http: HttpClient) {}

  putData() {
    const body = {
      updateKey: 'updateValue'
    };
    this.http.put('http://example.com/api/data/1', body).subscribe(response => {
      console.log(response);
    });
  }
}
  1. DELETE请求
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor(private http: HttpClient) {}

  deleteData() {
    this.http.delete('http://example.com/api/data/1').subscribe(response => {
      console.log(response);
    });
  }
}