Angular热observables和RxJS:数组的更改未发出给订阅者
创始人
2024-10-29 05:00:19
0

在 Angular 中,当我们使用 RxJS 来处理 Observable 时,有时我们会遇到热 observables 中的一些问题,如订阅者未能接收到对数组的更改。这是因为数组是对象,并且在 RxJS 中,对象是通过引用传递的,因此当我们更改数组时,它的引用仍然相同,而热 observable 不会自动地将更改推送给订阅者。

为了解决这个问题,我们可以使用 BehaviorSubject。BehaviorSubject 和普通的 Subject 是相似的,但是它会记录最新的值,并在订阅时将其推送给订阅者。因此,当我们使用 BehaviorSubject 时,订阅者在订阅时将收到最新的值,而不是最初的值。

下面是一个使用 BehaviorSubject 解决这个问题的例子:

import { Component, OnInit } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Component({
  selector: 'app-example',
  template: `
    
    
  • {{ item }}
`, }) export class ExampleComponent implements OnInit { items$ = new BehaviorSubject(['item 1', 'item 2', 'item 3']); ngOnInit() { // subscribe to the BehaviorSubject this.items$.subscribe(items => console.log(items)); } addItem() { // get the current value of the BehaviorSubject const currentItems = this.items$.value; // create a new array with the new item added const newItems = [...currentItems, `item ${currentItems.length + 1}`]; // update the BehaviorSubject with the new array this.items$.next(newItems); } }

在这个例子中,我们创建了一个 BehaviorSubject,并将默认值设置为一个包含三个字符串的数组。我们使用

相关内容

热门资讯

揭露透视!wepoker怎么提... 揭露透视!wepoker怎么提高运气,aapoker透视脚本下载,手段教程(有挂攻略)-哔哩哔哩所有...
解谜透视!hardrock作必... 解谜透视!hardrock作必弊!好像是真的有辅助教程(证实有挂)-哔哩哔哩1、超多福利:超高返利,...
详细透视!agpoker辅助,... 详细透视!agpoker辅助,hhpoker透视工具,步骤教程(有挂讲解)-哔哩哔哩hhpoker透...
普及透视!hardrock作必... 普及透视!hardrock作必弊!切实一直总是有辅助app(竟然有挂)-哔哩哔哩暗藏猫腻,小编详细说...
揭幕透视!红龙poker有辅助... 揭幕透视!红龙poker有辅助吗,哈糖大菠萝有挂吗,练习教程(真的有挂)-哔哩哔哩揭幕透视!红龙po...
详细透视!pokemmo修改器... 详细透视!pokemmo修改器手机版!一直真的是有辅助工具(有挂方法)-哔哩哔哩1、许多玩家不知道p...
总结透视!hhpoker是内部... 总结透视!hhpoker是内部控制吗,aapoker怎么开辅助器,操作教程(有挂功能)-哔哩哔哩hh...
教你透视!pokemmo辅助器... 教你透视!pokemmo辅助器手机版下载!一直是有辅助软件(详细教程)-哔哩哔哩1、每一步都需要思考...
辅助透视!sohoo辅助,po... 辅助透视!sohoo辅助,pokemmo脚本辅助下载,项目教程(有挂详细)-哔哩哔哩1、实时poke...
解密透视!智星德州有脚本吗!好... 解密透视!智星德州有脚本吗!好像真的有辅助软件(今日头条)-哔哩哔哩小薇(辅助器软件下载)致您一封信...