根据api响应关闭对话框组件

时间:2019-03-05 08:48:53

标签: angular angular-material angular6

我有一个名为AddCustomerComponent的组件,我称之为对话框组件,在AddCustomerComponent中,填写输入字段后,我正在执行 POST 操作。现在POST操作可以正常工作

但是在基于api响应的POST操作之后,我要执行以下操作:

  • 如果POST成功,则应该关闭 dialog(AddCustomerComponent)
  • 如果没有,则对话框不应关闭。

以下是我的组件代码和服务文件代码:

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);
    });
  }

}

4 个答案:

答案 0 :(得分:1)

您必须关闭对话框引用。我认为“ observable”是个不错的选择。 您的服务可能就是这样。

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { ICustomer } from 'src/app/models/app.models';
import { Observable} from 'rxjs';

@Injectable({
  providedIn: 'root',
})

export class CustomersService {
 private  baseUrl : string = '....api URL.....';

 constructor(private http: HttpClient) {}

  public async addCustomer(customer: ICustomer ): Observable<any>  {
    const apiUrl: string = `${this.baseUrl}/customers`;
    let temp : any;
    return this.http.post(apiUrl, customer);
  }

}

您的组件将如下所示。

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 dialogRef: MatDialogRef<AddCustomerComponent>
    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).subscribe((respons)=>{
   // validate the response here and then close the dialog
    // after successfull adding customer
    this.dialogRef.close();
    });

  }

}

答案 1 :(得分:1)

您应该使用服务返回的承诺。

const wheredata = [{
  field: {
    field: "email",
    datatype: "STRING",
    inputtype: "text",
    model: "User",
  },

  operator: "Op.eq",
  value: "myuser@gmail.com",
}, {
  field: {
    field: "createdAt",
    datatype: "DATE",
    inputtype: "date",
    model: "User",
  },
  operator: "Op.gt",
  value: "2015-12-12",
}];

const Sequelize = {
  Op: {
    gt: 'gt',
    eq: 'eq',
  },
};

const where = wheredata.reduce((tmp, x) => {
  tmp[x.field.field] = {
    [Sequelize.Op[x.operator.split('.')[1]]]: x.value,
  };

  return tmp;
}, {});

console.log(where);

}

答案 2 :(得分:1)

在这里订阅而不是在服务文件中订阅组件,以便您可以像下面那样应用条件。

Service.ts

 public addCustomer(customer: ICustomer ) : Observable<any>  {
    const apiUrl: string = `${this.baseUrl}/customers`;
    return this.http.post(apiUrl, customer);
  }

component.ts

 public onAddCustomer(): void {
    this.someCustomer = this.addForm.value;
    this.customersService.addCustomer(this.someCustomer).subscribe(data => {
        alert('Customer added successfully');
        this.dialogRef.close();
    },error => {
    // do not close dialog when error.
        console.log(error);
    });
  }

希望获得帮助!

答案 3 :(得分:1)

您只需要从服务中返回Post调用的承诺,并订阅该请求即可关闭对话框,无论http调用是否顺利。

首先,不要忘记在服务方法中返回您的承诺:

public addCustomer(customer: ICustomer ): Promise<void>  {
  const apiUrl: string = `${this.baseUrl}/customers`;
  return this.http.post(apiUrl, customer);
  // I removed the subscribe() here since you can have only one per promise
  // But you can use Rxjs 'pipe' operation if necessary.
}

然后,在调用addCustomer()方法时订阅Promise:

public onAddCustomer(): void {
  this.someCustomer = this.addForm.value;
  this.customersService.addCustomer(this.someCustomer).subscribe(
    () => // POST is ok, close dialog,
    (error) => // do nothing, or alert
  );
}