执行POST操作后刷新组件

时间:2019-03-21 10:54:54

标签: angular typescript angular6 angular-services

我有一个名为customers-list的组件,可在其中显示API中的所有客户:

customers-list.html

<div *ngFor="let customer of customers">
     <p>{{customer.name}</p>
</div>

customers-list.ts

import { Component Input} from '@angular/core';
import { ICustomer} from 'src/app/models/app.models';
import { CustomersService } from 'src/app/services/customers.service';

@Component({
  selector: 'drt-customers-list',
  templateUrl: './customers-list.component.html',
  styleUrls: ['./customers-list.component.scss'],
})
export class CustomerListComponent {
 public customers:  ICustomer[] ;

 constructor(public customersService: CustomersService,) {}

  public async ngOnInit(): Promise<void> {
    this.customers = await this.customersService.getCustomersList('');
  }

}

我还有一个名为add-customer的组件,我将在其中添加新客户,如下所示:

public onaddCustomer(): void {
    this.someCustomer = this.addCustomerForm.value;
    this.customersService.addCustomer( this.someCustomer).subscribe(
      () => { // If POST is success
        this.successMessage();
      },
      (error) => { // If POST is failed
        this.failureMessage();
      }
    );

  }

现在POST操作正常,但是customer-list不会在不刷新页面的情况下更新。

在成功完成customers-list操作之后,如何在不刷新整个页面的情况下更新POST组件?

服务文件:

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....';

  public async getCustomersList(): Promise<ICustomer[]> {
    const apiUrl: string = `${this.baseUrl}/customers`;

    return this.http.get<ICustomer[]>(apiUrl).toPromise();
  }

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

  return this.http.post(apiUrl, customer);
}


}

3 个答案:

答案 0 :(得分:1)

之所以不刷新,主要是因为ngOnIniit仅在初始化时执行。我假设您没有使用任何状态管理库(数据存储),所以最好的解决方案是在CustomerService中使用Subject。这是代码,它可能无法编译,我只是迅速在记事本中为您编写了代码。另外,您还需要确保添加方法确实添加了客户,而getCustomer方法确实获取了新添加的客户。如果两者都起作用,那么我的解决方案将起作用。

CustomerListComponent

import { Component Input} from '@angular/core';
import { ICustomer} from 'src/app/models/app.models';
import { CustomersService } from 'src/app/services/customers.service';

@Component({
  selector: 'drt-customers-list',
  templateUrl: './customers-list.component.html',
  styleUrls: ['./customers-list.component.scss'],
})
export class CustomerListComponent {
 public customers:  ICustomer[] ;

 constructor(public customersService: CustomersService,) {}

  public async ngOnInit(): Promise<void> {
    this.initCustomerAddedSubscription();
  }

/**
 * This subscription will execute every single time whenever a customer is added successfully
 *
 */ 
  public initCustomerAddedSubscription() {
    this.customersService.customerAdded.subscribe((data: boolean) => {
        if(data) {
            this.customers = await this.customersService.getCustomersList('');
        }
    });  

  }

}

CustomersService

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....';
 // use this subject in onAddCustomer method
 public   customerAdded: Subject<boolean>;

 // constructor to initialize subject
 constructor() {
    this.customerAdded = new Subject<boolean>();
 }
 public async getCustomersList(): Promise<ICustomer[]> {
    const apiUrl: string = `${this.baseUrl}/customers`;

    return this.http.get<ICustomer[]>(apiUrl).toPromise();
  }

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

  return this.http.post(apiUrl, customer);
}


}

onaddCustomer方法

public onaddCustomer(): void {
    this.someCustomer = this.addCustomerForm.value;
    this.customersService.addCustomer( this.someCustomer).subscribe(
      () => { // If POST is success
        // You can pass in the newly added customer as well if you want for any reason. boolean is fine for now.
        this.customersService.customerAdded.next(true);
        this.successMessage();
      },
      (error) => { // If POST is failed
        this.failureMessage();
      }
    );

  }

答案 1 :(得分:0)

ngOnInit仅运行一次。您已在ngOnInit中分配了客户变量。因此,它仅在刷新时更新。每次请求完成时,您都需要将值分配给this.customers

答案 2 :(得分:0)

constructor(public customersService: CustomersService, private cd: ChangeDetectorRef) {}
    public onaddCustomer(): void {
        this.someCustomer = this.addCustomerForm.value;
        this.customersService.addCustomer( this.someCustomer).subscribe(
          () => { // If POST is success
            this.customers = await this.customersService.getCustomersList('');
            console.log(this.customers) //are you getting updating list here without refreshing.
             this.cd.markForCheck();
          },
          (error) => { // If POST is failed
            this.failureMessage();
          }
        );

      }