首页 > 解决方案 > 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();
  }

}

标签: angulartypescriptrxjsobservable

解决方案


我没有看到对 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([...])
  {}

推荐阅读