Angularjs 使用 HTTP Post 发送数据

Oluwafisayo Oluwatayo 2023年1月30日
  1. 在 Angular 中使用响应类型 <any> 向 API 发布请求
  2. 在 Angular 中发布具有预期响应的请求
Angularjs 使用 HTTP Post 发送数据

在深入探讨本主题的真正要点之前,让我们先了解一下 http.post() 在 Angular 中的作用。当你想到 Google 时,我们在搜索时收到的搜索结果会使用 post 方法发送到服务器,当用户在 Google 上发起搜索时,会调用 get 方法。

所以在 Angular 中使用 http.post() 在服务器上存储数据。将停止此数据的服务器将具有一个 URL。

当程序员第一次遇到 $http.post() 时,尤其是有 jQuery 知识的人,第一反应是用 $http.post() 替换 $jQuery.post(),但这不起作用,因为 Angular 以不同的方式传输数据。

$http.post() 函数未正确应用时,将调用将要发送的 URL 数据,但不发送任何数据。让我们继续看看正确应用 HTTP Post 功能的不同方法。

在 Angular 中使用响应类型 <any> 向 API 发布请求

第一个示例将要求我们请求一个 URL,该 URL 返回分配给 Jason 的 id。响应类型是 <any>,因此它处理作为响应返回的任何属性。

我们有一个非常简单的 html 来设置。

<div>
  <h1>Angularjs HTTP POST</h1>
  <div>Post Id: {{ postId }}</div>
</div>

然后我们移动到 app.component.ts,我们将在其中导入 HttpClient,它将 HTTP 请求发送到 Angular。然后我们使用相同的 HttpClient 作为构造函数。

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({ selector: 'app-root', templateUrl: 'app.component.html' })
export class AppComponent implements OnInit {
  postId;

  constructor(private http: HttpClient) {}

  ngOnInit() {
    this.http
      .post<any>('https://reqres.in/api/users', {
        name: 'Jason',
      })
      .subscribe((data) => {
        this.postId = data.id;
      });
  }
}

最后我们前往 app.module.ts。在这里,我们将 HttpClientModule 导入到 Angular 中:

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

import { AppComponent } from './app.component';

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

如果一切按说明进行,你应该会看到 Post id,其中生成了三个数字。

在 Angular 中发布具有预期响应的请求

这种方法使用户可以更好地控制我们从 URL 获得的响应,因为我们可以分配我们想要获取的数据。我们将为此任务调用 interface Article 函数。

我们只对 app.component.ts 进行了微小的更改,我们将 <any> 替换为 <Article> 并在其下方创建 Article 函数。

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({ selector: 'app-root', templateUrl: 'app.component.html' })
export class AppComponent implements OnInit {
  postId;

  constructor(private http: HttpClient) {}

  ngOnInit() {
    this.http
      .post<Article>('https://reqres.in/api/users', {
        name: 'Jason',
      })
      .subscribe((data) => {
        this.postId = data.name;
      });
  }
}
interface Article {
id: number;
name: string;
}

HTTP 不是将 id 作为响应返回,而是分配给 id 的名称就是我们得到的。

Oluwafisayo Oluwatayo avatar Oluwafisayo Oluwatayo avatar

Fisayo is a tech expert and enthusiast who loves to solve problems, seek new challenges and aim to spread the knowledge of what she has learned across the globe.

LinkedIn