angular - Angular BehaviorSubject 订阅只触发一次
问题描述
我有一个带有名为must_checkout的布尔属性的 Angular 服务。我的服务还包含一个名为observable_must_checkout的属性,它是一个查看must_checkout的 BehaviorSubject 。
然后,在我的组件中,我订阅了observable_must_checkout。
这有效,并且组件在第一次must_checkout更改时收到事件。但是,这只触发一次,并且对must_checkout的后续更改不起作用:
服务:
import { Injectable, Input, Output } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
export class OrderingService
{
must_checkout: boolean;
observable_must_checkout = new BehaviorSubject<boolean>(this.must_checkout);
constructor([...])
{
this.observable_must_checkout = new BehaviorSubject<boolean>(this.must_checkout);
}
ChangeSomething()
{
console.log("changing the value here...");
this.must_checkout = true;
}
}
父组件:
import { Component, OnInit } from '@angular/core';
import { OrderingService } from 'src/app/services/ordering.service';
@Component({
selector: 'app-settle',
templateUrl: './settle.component.html',
styleUrls: ['./settle.component.css']
})
export class SettleComponent implements OnInit
{
constructor(private OrderingService: OrderingService) { }
ngOnInit()
{
this.basket = new OrderingService();
this.basket.observable_must_checkout.subscribe((newValue: boolean) => { alert("value changed: " + newValue) });
}
ngOnDestroy() {
this.basket.observable_must_checkout.unsubscribe();
}
}
解决方案
我没有看到对 next() 的调用,这是您向 BehaviorSubject 的当前订阅者触发新事件的方式。你正在寻找这样的东西。
ChangeSomething()
{
console.log("changing the value here...");
this.observable_must_checkout.next(true);
}
https://www.learnrxjs.io/subjects/
此外,您不需要在构造函数中初始化主题,因为您在上面的几行中执行了它:
observable_must_checkout = new BehaviorSubject<boolean>(this.must_checkout);
constructor([...])
{}
推荐阅读
- ios - 如何在数组中搜索对象?
- vue-formulate - 使用 VueFormulate 和 V-Calendar 自定义输入
- python - 特定于案例的混合?
- events - 如何在不实现视图的情况下处理草书事件
- linux - Bash - 如何通过常数增加正数并通过相同常数减少负数?(可能是 awk/sed)
- php - 从 DOM 表中删除子节点仅删除备用子节点
- php - 无法从 mysqli 查询中回显数据
- amazon-web-services - S3 不保留迁移数据的原始时间戳
- ruby-on-rails - 无法使用rails + undefined方法`projects'为nil创建和保存模型的新实例:NilClass - Thinbug
- python - 我如何使用 Selenium Python 重定向(导航)到新的 url