动态修改行为主题流

Modify Behavior Subject stream dynamically

我遇到了一种情况,我想动态地添加一个 属性 到 BehaviorSubject<any[]> 中的某个对象。我得到了组件 A 和 B,其中 A 订阅了可观察到的服务。我需要能够以某种方式操纵来自组件 B 的流,我将在其中将一些道具附加到 BehaviorSubject 中该数组的索引项。

组件 A:

.html

<pre>{{ data$ | async | json }}</pre>

.ts

export class DummyComponent implements OnInit {
  data$: Observable<any>;

  constructor(private dummyService: DummyService) { }

  ngOnInit() {
    this.data$ = this.dummyService.someData$;
  }
}

组件 B:

.html

<button (click)="foo()">Click</button>

.ts

export class Dummy2Component {

  constructor(private dummyService: DummyService) { }

  foo() {
    this.dummyService.someAction(0, () => {
      console.log('test');
    });
  }
}

数据服务(虚拟服务):


export const someRandomData = [
  {
    id: 1,
    label: 'foo'
  },
  {
    id: 2,
    label: 'bar'
  }
]

@Injectable()
export class DummyService {
  private someDataSource$: BehaviorSubject<any> = new BehaviorSubject(someRandomData);
  someData$: Observable<any> = this.someDataSource$.asObservable();

  someAction(index: number, fn: () => void): void {
    this.someData$ = this.someData$.pipe(
      map(items => {
        console.log(items);
        items[index].onClick = fn;
        return items;
      })
    )
  }
}

在组件 B 中,我得到了调用 foo() 函数的按钮,并且该函数被执行,但是当它在 DummyService 中调用 someAction() 时,它不会修改流。该流保持不变。它永远不会 console.logs(item) 即使在组件 A 中订阅了 someData$。

不确定我在这里遗漏了什么。

这是 stackblitz 演示:https://stackblitz.com/edit/angular-zyr5r6

您不应将流替换为另一个流,而应分派一个新值:

someAction(index: number, fn: () => void): void {
  const items = this.someDataSource$.value;
  items[index].onClick = 'fn';
  this.someDataSource$.next([...items]);
}

这里的另一个问题是您不会看到任何 UI 更改,因为您使用 json 管道。并且函数对任何序列化程序都不可见。

Forked Stackblitz