【发布时间】:2019-03-05 08:48:52
【问题描述】:
我有一个名为 AddCustomerComponent 的组件,我将其调用为对话框组件,在填充输入字段后的 AddCustomerComponent 中,我正在执行 POST 操作。现在 POST 操作工作正常。
但是在基于api响应的POST操作之后,我想执行以下操作:
- 如果 POST 成功,则 dialog(AddCustomerComponent) 应该关闭。
- 如果没有,则对话框不应关闭。
下面是我的component代码和service文件代码:
HTML
<form [formGroup]="addForm">
<mat-form-field>
<input matInput placeholder="Name" formControlName="name" required>
<mat-error *ngIf="addCusForm.controls.name.hasError('required')">
Please enter your name
</mat-error>
</mat-form-field>
<mat-form-field>
<input placeholder="Email Address" formControlName="email" required>
<mat-error *ngIf="addCusForm.controls.email.hasError('required') ">
Please enter email address
</mat-error>
</mat-form-field>
<button mat-flat-button type="submit" (click)="onAddCustomer()">Save</button>
<button mat-flat-button type="button">Cancel</button>
</form>
TS
import { Component, OnInit } from '@angular/core';
import {
FormBuilder,
FormGroup,
Validators,
} from '@angular/forms';
import { MatDialog, MatDialogRef } from '@angular/material';
import { ICustomer } from 'src/app/models/app.models';
import { CustomersService } from 'src/app/services/customers.service';
@Component({
selector: 'awa-add-customer',
templateUrl: './add-customer.component.html',
styleUrls: ['./add-customer.component.css'],
})
export class AddCustomerComponent implements OnInit {
public addForm: FormGroup;
public someCustomer: ICustomer;
constructor(
private fb: FormBuilder,
public dialog: MatDialog,
public customersService: CustomersService,
) {}
public ngOnInit(): void {
this.addForm = this.fb.group({
name: [null,[Validators.required]],
email: [null,[Validators.required]],
});
}
public onAddCustomer(): void {
this.someCustomer = this.addForm.value;
this.customersService.addCustomer(this.someCustomer);
}
}
服务文件
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { ICustomer } from 'src/app/models/app.models';
@Injectable({
providedIn: 'root',
})
export class CustomersService {
private baseUrl : string = '....api URL.....';
constructor(private http: HttpClient) {}
public async addCustomer(customer: ICustomer ): Promise<void> {
const apiUrl: string = `${this.baseUrl}/customers`;
let temp : any;
temp = this.http.post(apiUrl, customer).subscribe(data => {
alert('Customer added successfully');
},error => {
console.log(error);
});
}
}
【问题讨论】:
-
从服务返回承诺,并使用
then(),catch()处理组件中的响应/错误 -
为什么要将所有方法都设置为公开?
标签: angular angular-material angular6