当前位置: 首页 > 知识库问答 >
问题:

在执行POST操作后刷新组件

邢财
2023-03-14

我有一个名为“客户列表”的组件,其中显示了API中的所有客户:

客户列表。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('');
  }

}

我有另一个名为“添加客户”的组件,我将在其中添加新客户,如下所示:

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操作正常,但如果不刷新页面,则不会更新客户列表。

如何在成功执行POST操作后更新client-list组件,而无需刷新整个页面?

服务文件:

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个答案

国高杰
2023-03-14
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();
          }
        );

      }
丌官浩旷
2023-03-14

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

靳举
2023-03-14

它没有刷新的主要原因是ngOnIniit仅在初始化时执行。我假设您没有使用任何状态管理库(数据存储),所以最好的解决方案是在CustomerService中使用主题。这是代码,可能无法编译,我只是快速地在记事本中为您编写了它。此外,您需要确保add方法确实是在添加客户,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);
}


}

客户方法

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

  }
 类似资料:
  • 我有一个猫鼬模式 我最初设置了名称和电话字段的集合。我需要将集合更新为消息数组中的新消息和新地址到地址对象中。该函数还必须处理任何单个操作,即在某些情况下我只更新到消息数组或更新到名称和地址。所以我如何在单个函数中执行所有操作。

  • 编辑:编辑标题以反映新发现。第二个portlet是什么类型的portlet并不重要。请参见下面的一般行为: 我在页面上有一个Struts2 portlet a,它的默认“索引”操作是pageA1 症状: 我在strut操作中添加了一些日志记录来显示传递的参数。在正常导航期间(即。我只是使用struts2 portlet A本身),显示参数struts.portlet.action和struts.p

  • 问题内容: 用户成功登录后,我需要执行一组操作。这包括从数据库加载数据并将其存储在会话中。 实现此目的的最佳方法是什么? 问题答案: 您可以向事件添加侦听器。 像这样附加您的听众。在此示例中,我还将安全性上下文和会话作为依赖项传递。 注意: 从Symfony 2.6开始不推荐使用SecurityContext。请参考 http://symfony.com/blog/new-in-symfony-2

  • 问题内容: 在Java方法中,我想使用Jersey客户端对象在RESTful Web服务(也使用Jersey编写)上执行POST操作,但不确定如何使用客户端发送将用作FormParam的值在服务器上。我能够发送查询参数就好了。 问题答案: 我自己尚未完成此操作,不过Google- Fu的简短内容在blogs.oracle.com上提供了一个技术提示,其中包含您真正要求的示例。 摘自博客文章的示例:

  • 问题内容: 伙计们,我想在mysql中使用解析函数滞后。在Oracle中受支持,但在Mysql中无法做到。那么有人可以帮助我如何在Mysql中执行滞后运算吗?例如 我想使用滞后函数,以便我的输出如下 Mysql支持滞后功能吗??? 问题答案: 您可以使用用户变量来模拟它: 看到它在工作sqlfiddle直播 在这里,您可以初始化变量。这与在编写查询之前编写内容相同。 那么这些语句在select子句

  • 我有一个执行一些网络操作的自定义视图。视图根据该操作结果构建UI。 该视图包含通过Internet获取的卡的列表。此视图用于多个地方。假设其中一个是我的碎片。 下面是我在Fragment中的操作: 我的自定义视图如下所示: 好了,现在当用户从我的应用程序切换到另一个应用程序时,我的碎片可能会被销毁。我想保存我的自定义视图的状态。因此,我的观点不需要再从互联网上获取信息。因此,我在中附加了以下数据(