【问题标题】:Angular and Typescript Sending Post RequestAngular 和 Typescript 发送帖子请求
【发布时间】:2019-04-26 07:43:45
【问题描述】:

我有一个简单的页面,带有 angular 和 typescript,只有 1 个按钮和 1 个文本字段。我想向一个链接发出一个发布请求,该链接发布在文本框中写入的字符串。

我的按钮 html:

 <a class="button-size">
      Add Customer
    </a>

和按钮ts文件:

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

@Component({
  selector: 'customer-button123',
  templateUrl: './blabla',
  styleUrls: ['./clacla']
})
export class AddCustomerButtonComponent implements OnInit {
  constructor() { }
  ngOnInit() {
  }
}

文本框html:

<mat-form-field>
  <input matInput placeholder="Customer Name">
</mat-form-field>

文本框ts文件:

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

@Component({
  selector: 'customer-text-field',
  templateUrl: './blabla2',
  styleUrls: ['./clacla2']
})
export class CustomerTextFieldComponent implements OnInit {
  constructor() { }
  ngOnInit() {
  }
}

简单的包装页面html是:

<div class="input-label">
    <mg-customer-text-field></mg-customer-text-field>
</div>

<div>
  <mg-customer-button123></mg-customer-button123>
</div>

如何发送帖子请求以链接 localhost8080/admin/addCustomer?

【问题讨论】:

  • 我没有看到任何数据绑定...
  • 您能帮我缩小您的问题范围吗?您是否需要帮助来获取 组件的值或使用数据加载发出 Post 请求或两者兼而有之?
  • 您在单独的页面中创建了按钮,在单独的页面中创建了文本表单,您尝试在单独的页面中创建?
  • 您可能需要一个服务来为您执行此操作,您的按钮应该调用在您的 .component.ts 上定义的函数,而不是该组件调用您服务的函数,要创建此函数,请查看HttpClient 示例,非常简单。

标签: html angular typescript frontend


【解决方案1】:

您使用HttpModule

我使用服务来分隔 http 请求。

示例

import { Component, OnInit } from '@angular/core';
import { ApiService } from '../../services/api.service';

@Component({
  selector: 'customer-button123',
  templateUrl: './blabla',
  styleUrls: ['./clacla']
})
export class AddCustomerButtonComponent implements OnInit {

data: any;
results: any;

  constructor(private apiService: ApiService) { }
  ngOnInit() {
  }
    getDataFromApi() {
      this.apiService.getData(this.data).subscribe(results => {
        this.results = results;
    });
 }

ApiService

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

@Injectable({
  providedIn: 'root'
})
export class ApiService {
  apiUrl: string = environment.apiUrl;
  constructor(private http: HttpClient) {}

getData(data): any {
  return this.http.get(`http://localhost:8080/api/get-data`);
}

html

<div class="input-label">
  <mg-customer-text-field [(ngModel)]="data"></mg-customer-text-field>
</div>

<div>
  <mg-customer-button123 (click)="getDataFromApi()"></mg-customer-button123>
</div>

【讨论】:

    【解决方案2】:

    如果您将前端托管在端口:4200(默认 Angular 端口服务)并且您想向 http://localhost8080/admin/addCustomer 发送请求,您将需要代理配置。您可以在这里查看更多信息:https://itnext.io/angular-cli-proxy-configuration-4311acec9d6f

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-23
      • 2012-10-07
      • 2015-08-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-10
      • 1970-01-01
      相关资源
      最近更新 更多