【问题标题】:Simple Post Request in Angular 2 with type or modelAngular 2中带有类型或模型的简单发布请求
【发布时间】:2020-09-29 06:43:34
【问题描述】:

现在我正在尝试提出一个简单的发布请求。这是表格

<label for="name">Name</label>
<input type="text" id="value" [(ngModel)]="value" />
<input type="button" value="Get Name" (click)="getName(value)" />

这里是 .ts

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

@Component({
    selector: 'app-home',
    templateUrl: './add-name.component.html'
})

export class FetchNameComponent {
    chosenName: string;
    constructor(
        private http: HttpClient
    )
    {
    }

    getName(value): void {
        this.chosenName = value
        alert(this.chosenName)
        this.http.post("NameItem", this.chosenName).subscribe(result => {
            console.log(result);
        }, error => console.error(error));
    }
}

我的警报向我显示了正确的值,所以我知道到目前为止一切都很好

这是我的控制器

   [HttpPost]
        public String Post(String chosenName)
        {
            string newName = chosenName + "123";
            return newName;
        }

chosenName 始终为 null,因此有问题。我很好奇如何使用 angular2 将类型和对象发送到 post 请求中

如果我想通过它发送一个对象,它看起来是否相似?

【问题讨论】:

    标签: angular typescript post model-view-controller angular2-forms


    【解决方案1】:

    我假设后端是 C# .net。如果是这样,您的 api 将期望在您的查询字符串中出现“chosenName”。所以,你发布的网址应该是,/apiUrl/?chosenName="somename"

    因此,您的发布请求应如下所示:

    this.http.post("/apiUrl/?chosenName=" + this.choosenName).subscribe(result => {
        console.log(result);
    }, error => console.error(error));
    

    但是如果你想在数据中而不是在 url 中发布它,你可能需要修改你的 api。这是good article

    然后,你可以通过 post 传递更复杂的对象:

    const data = {chooseName: this.chooseName, anotherValue: "someValue"};
    this.http.post("/apiUrl/", data).subscribe(result => {
        console.log(result);
    }, error => console.error(error));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-16
      • 1970-01-01
      相关资源
      最近更新 更多