Angular11中如何通过Web API服务无刷新展示新增记录行
Angular11 无刷新展示新增记录实现方案
现有代码只实现了页面初始化时单次拉取员工列表,要实现无刷新自动更新最新数据,可以根据实际场景选择以下方案:
方案1:短轮询(无需改造后端,快速实现)
通过定时重复拉取接口更新列表,适合对实时性要求不高的场景,默认3秒拉取一次可自行调整间隔。
修改 service.ts
新增轮询方法,引入rxjs的interval和switchMap操作符:
import { interval, switchMap } from 'rxjs'; constructor(private http: HttpClient) { } public getEmp_ServiceFun(): Observable<Employee[]> { return this.http.get<Employee[]>(this.serverUrl + 'employees') .pipe( catchError(this.handleError) ); } // 新增轮询获取接口 public getEmpPolling_ServiceFun(intervalMs = 3000): Observable<Employee[]> { return interval(intervalMs).pipe( switchMap(() => this.getEmp_ServiceFun()), catchError(this.handleError) ); }
修改 component.ts
处理订阅逻辑,新增销毁逻辑避免内存泄漏:
import { Subject, takeUntil } from 'rxjs'; // 声明销毁触发器,用于取消所有订阅 private destroy$ = new Subject<void>(); employees: Employee[] = []; error = ''; ngOnInit() { // 初始化先拉取一次数据 this.loadEmployeeList(); // 开启轮询 this.employeeservice.getEmpPolling_ServiceFun() .pipe(takeUntil(this.destroy$)) .subscribe({ next: (data: Employee[]) => this.employees = data, error: err => this.error = err }); } // 封装列表拉取方法,方便后续手动调用 private loadEmployeeList() { this.employeeservice.getEmp_ServiceFun() .pipe(takeUntil(this.destroy$)) .subscribe({ next: (data: Employee[]) => this.employees = data, error: err => this.error = err }); } ngOnDestroy() { // 组件销毁时释放订阅资源 this.destroy$.next(); this.destroy$.complete(); }
方案2:新增操作后主动拉取(配合轮询使用,提升实时性)
如果你的页面有新增员工的提交逻辑,可以在新增接口调用成功后,立刻手动拉取一次列表,不需要等待轮询间隔,用户提交完即可看到最新数据:
// 你的新增员工提交方法示例 addEmployee(newEmp: Employee) { this.employeeservice.addNewEmp(newEmp).subscribe({ next: () => { // 新增成功后立刻刷新列表 this.loadEmployeeList(); }, error: err => this.error = err }) }
方案3:WebSocket 推送(性能最优,实时性最高,需要后端配合)
如果对实时性要求很高、不想产生过多无效请求,可以对接WebSocket或SSE服务,后端有新增记录时主动推送给前端,前端接收到数据后直接更新本地列表即可:
// component.ts 示例逻辑 ngOnInit() { // 初始化拉取一次全量列表 this.loadEmployeeList(); // 监听后端推送的新增员工数据 this.websocketService.listen<Employee>('newEmployeeAdded') .pipe(takeUntil(this.destroy$)) .subscribe(newEmp => { // 直接把新记录推入本地数组,不需要全量拉取 this.employees.unshift(newEmp); }) }
内容的提问来源于stack exchange,提问作者Muhammad Bilal
相关产品推荐
相关产品推荐

