首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >需要使用web服务显示Angular11中新添加的记录/行,而不需要刷新页面。

需要使用web服务显示Angular11中新添加的记录/行,而不需要刷新页面。
EN

Stack Overflow用户
提问于 2021-06-23 06:54:05
回答 2查看 80关注 0票数 0

Component.ts

代码语言:javascript
复制
ngOnInit() {
    this.employeeservice.getEmp_ServiceFun().subscribe(
      (data: Employee[]) => this.employees = data,
      error => this.error = error
    );
  }

service.ts

代码语言:javascript
复制
constructor(private http: HttpClient) { }

  public getEmp_ServiceFun(): Observable<Employee[]> {

    return this.http.get<Employee[]>(this.serverUrl + 'employees')
    .pipe(
      catchError(this.handleError)
      );
  }
EN

回答 2

Stack Overflow用户

发布于 2021-07-01 14:50:34

再次运行ngoninit方法对我来说有点奇怪,因为它只运行一次。我会用一个可观察的间隔来包装员工服务方法。不过,别忘了取消订阅。否则,它会一直调用getEmp_ServiceFun,直到整个应用程序关闭为止。

代码语言:javascript
复制
ngOnInit() {
    interval(1000).pipe(
        map(() => {this.employeeservice.getEmp_ServiceFun().subscribe(
            (data: Employee[]) => this.employees = data,
            error => this.error = error
        );})}

这将取代整个数组,而不仅仅是添加到其中。我将再次查看getEmp_ServiceFun,以便您只需要新数据,而不是所有数据,然后将其推送到数组中。

编辑:更好的办法是不要在地图上订阅,而是把它移到管道后面。您可能需要使用switchMap

票数 1
EN

Stack Overflow用户

发布于 2021-06-30 07:06:13

我使用setTimeout()刷新一个组件,它运行得很好,但是现在我只需要检查一下,它是否有良好的实践?

代码语言:javascript
复制
ngOnInit() {
      this.employeeservice.getEmp_ServiceFun().subscribe(
        (data: Employee[]) => this.employees = data,
        error => this.error = error
      );
    //refresh this component
    this.timeout = setTimeout(() => { this.ngOnInit() }, 1000 * 1)
  }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68094923

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档