Component.ts
ngOnInit() {
this.employeeservice.getEmp_ServiceFun().subscribe(
(data: Employee[]) => this.employees = data,
error => this.error = error
);
}service.ts
constructor(private http: HttpClient) { }
public getEmp_ServiceFun(): Observable<Employee[]> {
return this.http.get<Employee[]>(this.serverUrl + 'employees')
.pipe(
catchError(this.handleError)
);
}发布于 2021-07-01 14:50:34
再次运行ngoninit方法对我来说有点奇怪,因为它只运行一次。我会用一个可观察的间隔来包装员工服务方法。不过,别忘了取消订阅。否则,它会一直调用getEmp_ServiceFun,直到整个应用程序关闭为止。
ngOnInit() {
interval(1000).pipe(
map(() => {this.employeeservice.getEmp_ServiceFun().subscribe(
(data: Employee[]) => this.employees = data,
error => this.error = error
);})}这将取代整个数组,而不仅仅是添加到其中。我将再次查看getEmp_ServiceFun,以便您只需要新数据,而不是所有数据,然后将其推送到数组中。
编辑:更好的办法是不要在地图上订阅,而是把它移到管道后面。您可能需要使用switchMap
发布于 2021-06-30 07:06:13
我使用setTimeout()刷新一个组件,它运行得很好,但是现在我只需要检查一下,它是否有良好的实践?
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)
}https://stackoverflow.com/questions/68094923
复制相似问题