在执行POST操作后刷新组件

问题描述 投票:0回答:3

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

客户-list.html

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

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


}
angular typescript angular6 angular-services
3个回答
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('');
        }
    });  

  }

}

客户服务

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

  }

0
投票

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


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

      }
© www.soinside.com 2019 - 2024. All rights reserved.