【问题标题】:To close dialog component based on api response根据 api 响应关闭对话框组件
【发布时间】: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


【解决方案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
  );
}

【讨论】:

  • 您的解决方案工作正常,感谢 ans,但如果我在 addCustomer 方法中添加 Promise&lt;void&gt; service file.it 显示此 lint 错误:[ts] Type ' Observable' 缺少类型“Promise”的以下属性:然后,catch,[Symbol.toStringTag]
  • 我从您的方法中删除了async 关键字,因为您在调用它时没有使用awaitasync 自动返回一个 Promise,现在你返回一个 Observable :) 如果你更喜欢使用 Promise,你应该尝试调用 this.http.post(...).toPromise()
【解决方案2】:

你必须关闭对话框引用。我认为 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();
    });

  }

}

【讨论】:

  • 请完整阅读我的问题,我想关闭对话框based upon api response,我知道如何在单击button 时关闭对话框。
  • 好吧,让我试试。
【解决方案3】:

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

public onAddCustomer(): void {
this.someCustomer = this.addForm.value;
this.customersService.addCustomer(this.someCustomer)
  .then(
    // add success code here
  )
  .catch(
    // add error code here
  )

}

【讨论】:

    【解决方案4】:

    这里不是订阅服务文件,而是订阅您的组件,以便您可以应用您的条件,如下所示。

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

    希望对您有所帮助!

    【讨论】:

      猜你喜欢
      • 2015-05-08
      • 2021-03-31
      • 2020-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-30
      • 1970-01-01
      • 2018-01-04
      相关资源
      最近更新 更多