Angular应用中的声明式和反应式方法之间的摩擦

问题描述 投票:2回答:1

这是我经常遇到的一个问题,当我的应用由声明性组件组成时(因此它们的模板可以通过其属性的值完全可预测),但有时某个主体会以一种被动的方式推动新的价值。

比方说,我有这样的东西:一个基于数组元素的组件列表。

<hello *ngFor="let h of helloComponents"></hello>

hello组件已从服务预订到BehaviorSubject。

[在某个时候(例如,单击按钮时)behaviorSubject会发出新值,但数组也会更新。

事件的顺序如下:

  1. 主题发出新的值
  2. 订阅该主题的组件将获得新值
  3. 数组已更新,新组件已初始化,它们从主题接收新值作为第一个值

问题是旧组件在被销毁之前就已接收到该值,因此它们可能会运行我不希望它们执行的代码,因为它们在第3点被销毁了。

如果我先更新数组,然后从主题推送新值,则情况不会改变。

我找到2个修复程序:

A。使用setTimeout可以确保当旧组件已被Angular Change Detection销毁时,主体会发出新值。但是我不知道这个解决方案有多强大...

this.myarray= [4, 5];
setTimeout(() => subject.next(new value));

B。使用observeOn(asyncScheduler)

this.stateService.state$.pipe(
        observeOn(asyncScheduler)
    ).subscribe(
      state => console.log(`helloComponent ${this.id}, state: ${state}`)
    )

但是我真的是一个关于Rxjs Scheduler的新手,我不知道这是一个好方法还是有更好的选择。

Here is the stackblitz... open the console

有什么想法吗?

angular rxjs reactive-programming scheduler
1个回答
0
投票
我将跟踪与手动更改检测结合使用(可能看起来很粗糙,但是您正在手动更新helloComponents数组,它似乎可以正常工作:

import { Component, ChangeDetectorRef } from '@angular/core'; import { StateService } from './state.service'; @Component({ selector: 'my-app', template: `<hello *ngFor="let h of helloComponents, trackBy: trackById" [id]="h"></hello> <button (click)="action()">action</button>` }) export class AppComponent { name = 'Angular'; helloComponents = [1, 2, 3]; constructor(private stateService: StateService, private ref: ChangeDetectorRef) {} action() { this.helloComponents = [4, 5]; this.ref.detectChanges(); this.stateService.action(); } trackById = id => id; }

stackblitz:https://stackblitz.com/edit/angular-e9zfoq?file=src/app/app.component.ts
© www.soinside.com 2019 - 2024. All rights reserved.