Angular9中多次订阅单个next的行为主体
创始人
2024-10-22 17:00:55
0

当在 Angular 9 中多次订阅一个行为主体的单个 next 时,可以采用以下方法解决:

1.使用 pipe(share):

share 算子可让订阅者共享 obervable 的执行结果,从而减少多余的订阅。使用该算子可以避免多次触发 next。

import { BehaviorSubject } from 'rxjs'; import { share } from 'rxjs/operators';

export class MyComponent { myBehaviorSubj = new BehaviorSubject('default value');

getData() { return this.http.get('my/api/endpoint').pipe( share() ); }

myMethod() { this.getData().subscribe(response => { console.log(response); this.myBehaviorSubj.next(response.someProperty); }); } }

2.取消先前的订阅:

如果您确实需要多次订阅单个 next,但每次订阅前都要取消先前的订阅。这样可确保只有一个订阅者会收到通知。

import { BehaviorSubject } from 'rxjs';

export class MyComponent { myBehaviorSubj = new BehaviorSubject('default value'); subscription: Subscription;

myMethod() { if (this.subscription) { // 取消前一个订阅 this.subscription.unsubscribe(); }

const newSub = this.myBehaviorSubj.subscribe(value => {
  console.log(value);
});

this.myBehaviorSubj.next('new value');
this.subscription = newSub; // 将新的订阅存储到组件的变量中

} }

相关内容

热门资讯

透视app!wepoker买钻... 透视app!wepoker买钻石有用吗(透视)wepoker辅助器安装包(都是存在有透视)-哔哩哔哩...
透视神器!wepoker手机版... 透视神器!wepoker手机版透视脚本(透视)wepoker辅助工具(竟然一直都是有透视)-哔哩哔哩...
透视教程!wepoker免费脚... 透视教程!wepoker免费脚本(透视)wepoker免费辅助器(总是有挂)-哔哩哔哩1、玩家可以在...
透视app!wepokerpl... 透视app!wepokerplus作必弊(透视)wepoker透视是真的吗(真是有脚本)-哔哩哔哩一...
透视工具!德扑之心免费透视(透... 透视工具!德扑之心免费透视(透视)德普之星怎么开辅助(果然一直都是有脚本)-哔哩哔哩1、德普之星怎么...
透视app!wepoker线上... 透视app!wepoker线上大神(透视)黑侠破解wepoker(都是是有辅助器)-哔哩哔哩1.黑侠...
透视方法!hhpoker作必弊... 透视方法!hhpoker作必弊码怎么用(透视)hhpoker透视脚本下载(一贯真的有挂)-哔哩哔哩1...
透视app!德普之星的辅助工具... 透视app!德普之星的辅助工具介绍(透视)德普之星辅助工具如何设置(其实是有透视)-哔哩哔哩1、在德...
透视教程!越乡游义乌辅助器(辅... 透视教程!越乡游义乌辅助器(辅助)圣游辅助软件(原来是真的有辅助器)-哔哩哔哩1、起透看视 越乡游义...
透视攻略!hhpoker是正品... 透视攻略!hhpoker是正品吗(透视)hhpoker真的有透视吗(确实真的有挂)-哔哩哔哩1、hh...