【问题标题】:(Angular 12) Search button response data is not show in template before Click the button twice(Angular 12)搜索按钮响应数据在单击按钮两次之前未显示在模板中
【发布时间】:2021-12-17 12:35:36
【问题描述】:

这是我的搜索输入框和按钮

  <div class="col-lg-8">
    <input #text class="form-control" placeholder="Search Customer" required/>
  </div>

  <button type="button" class="btn btn-info me-2" (click)="searchData(text)">Search</button>

这是我在控制台中获得值的组件代码

   searchData(text:any){
     this.service.searchCustomer(text.value).subscribe(
       response =>{
         this.list = response;
         console.log(this.list); 
         this.cData = this.list.data.model;
        }
  );
}

这是我返回的服务

    searchCustomer(text:string){
      let body ={"searchText":text}
       return this.http.post(this.baseUrl+'/search-customer', body);
      }

【问题讨论】:

  • 你能具体说明你遇到了什么错误吗?
  • 使用 ChangerefDetector ,它会刷新你的数据绑定。我相信它会解决您的问题
  • @YongShun 我没有一键显示模板中的数据

标签: angular angular2-services angular10 angular11 angular12


【解决方案1】:

它工作正常我在这个函数的搜索数据中输入了一个警报,我得到了我在那个函数中输入的警报

一键式

你必须放入你的构造函数

constructor(private changeRef: ChangeDetectorRef) {}

searchData(text:any){
 this.service.searchCustomer(text.value).subscribe(
   response =>{
     this.list = response;
     console.log(this.list); 
     this.cData = this.list.data.model;
     this.changeRef.detectChanges(); // this line detect changes
    })
;}

【讨论】:

  • 一切正常,但我需要一键在 html 中呈现这些数据。谢谢
  • 好的,所以你必须在你的构造函数中添加一行constructor( private changeRef: ChangeDetectorRef, ){}在你的点击函数中,数据添加这一行functionName(){ // your response data after add this line this.changeRef.detectChanges(); }
  • @divraj 用代码更新你的答案
  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
  • 我更新了您要求的代码,您可以检查一下,如果您对该代码有任何问题,请告诉我。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-21
  • 1970-01-01
  • 2021-07-28
  • 2019-07-25
相关资源
最近更新 更多