常用HTTP请求方法
- GET:用于从服务器获取数据。
- POST:用于向服务器提交数据,通常用于创建新资源。
- PUT:用于更新服务器上的资源。
- DELETE:用于从服务器删除资源。
使用HttpClient
模块传递参数示例
- 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);
});
}
}
- 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);
});
}
}
- 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);
});
}
}
- 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);
});
}
}