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软件安装包)辅助神器app还具备辅助透视行为开挂功能,通过对客户w...
透视ai"pokem... 1、透视ai"pokemmo手机版透视脚本"详细辅助系统教程(确实是有挂);详细教程。2、pokem...
玩家必看科普!哈糖大菠萝怎么挂... 玩家必看科普!哈糖大菠萝怎么挂,hardrock透视工具,科技教程(有挂攻略)关于哈糖大菠萝怎么挂机...
透视好友房"wepo... 透视好友房"wepokerplus作弊"详细辅助黑科技教程(素来有挂);最新版2024是一款经典耐玩...
最新通报!wepoker免费钻... 最新通报!wepoker免费钻石,约局吧开挂,切实教程(有挂技巧);亲真的是有正版授权,小编(透视辅...
透视有挂"wpk作弊... 透视有挂"wpk作弊最怕三个东西"详细辅助规律教程(素来是真的有挂)1、许多玩家不知道wpk作弊最怕...
玩家必看秘籍!wepoker透... 玩家必看秘籍!wepoker透视最简单三个步骤,wepoker辅助脚本,扑克教程(有挂技巧);实战中...
透视神器"we po... 透视神器"we poker辅助器下载"详细辅助攻略教程(素来真的有挂);大神普及一款德州ai内幕,确...
必备教程!wepoker到底有... 必备教程!wepoker到底有没有透视,aapoker公共底牌,曝光教程(有挂教程);最新版2024...
透视系统"aapok... 此外,数据分析德州(aapoker插件下载)辅助神器app还具备辅助透视行为开挂功能,通过对客户aa...