Angular和Typescript发送帖子请求

时间:2018-11-23 17:44:16

标签: html angular typescript frontend

我有一个简单的页面,带有角和打字稿,只有一个按钮和一个文本字段。我想对发布张贴在文本框中的字符串的链接发出发布请求。

我的按钮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?

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

您使用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>