angular 9/8 AJAX get和Post请求示例

分享于 

4分钟阅读

Angular

  繁體

在这篇文章中,创建一个简单的示例,将Angular 9/8和HttpClient请求发送到Ajax get和Post。

导入HttpClientModule

HttpClientModule是导出HttpClient服务的模块,因此需要在项目中导入它。

打开src/app/app.module.ts文件,并按如下方式更新它:


import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';

@NgModule({
 declarations: [
 AppComponent,
 ],
 imports: [
 BrowserModule,
 AppRoutingModule,
 HttpClientModule
 ],
 providers: [],
 bootstrap: [AppComponent]
})
export class AppModule { }

我们只需要从HttpClientModule导入@angular/common/http,并将它添加到importsNgModule数组中。

生成Angular服务

在终端中,只需从项目的文件夹中执行以下命令:


$ ng generate service http

转到src/app/http.service.ts文件,并导入HttpClient


import { HttpClient } from '@angular/common/http';

接下来,使用http服务的构造函数注入HttpClient


import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

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

 constructor(private httpClient: HttpClient) { }
}

好了,我们准备在应用程序中发送get和post请求。

发送Ajax get请求

首先定义一个服务方法,以便向服务器发送get请求以获取一些数据:


import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

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

 apiUrl = "/api/endpoint";
 constructor(private httpClient: HttpClient) { }

 sendGetRequest() {
 return this.httpClient.get(this.apiUrl);
 }
}

假设端点返回以下数据:


[
 { id: '1', name: 'Product 1'}, 
 { id: '2', name: 'Product 2'}
] 

发送Ajax POST请求

接下来,定义一个发送post请求的方法:


import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';


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

 apiUrl = "/api/endpoint";
 constructor(private httpClient: HttpClient) { }

 sendPostRequest(data: Object): Observable<Object> {
 return this.http.post(this.apiUrl, data);
 }
}

接下来需要将HttpService注入到组件中,并调用方法,但要真正地将请求发送到服务器,你需要订阅定义方法的RxJS observables,例如:


this.httpService.sendGetRequest().subscribe((responseBody) => {
 console.log(responseBody);
});