无法在 Angular 中使用 Behavior Subject 在服务的不相关组件之间共享数据

Unable to share data between unrelated components from a service using Behavior Subject in Angular

我是 Angular 的新手。我有一个购物车服务和两个不相关的组件 - ProductList 组件和 Nav 组件。我订阅了这两个组件中的服务,更新了 ProductList 组件中的购物车计数,但 Nav 组件仍显示初始计数而不是更新后的计数。有谁能帮忙吗

@Injectable()
export class CartService {

  private initialCount = new BehaviorSubject<number>(0);
  currentCount = this.initialCount.asObservable();
  //cartCount : BehaviorSubject<number>= new BehaviorSubject<number>(0);

  changeCount(count: number) : number {
    this.initialCount.next(count);
    console.log("count in cart service ::: "+count);
    return count;
  }

}

ProductList 组件:

export class ProductListComponent{

    count : number;

    constructor(private _cartService : CartService){}

    ngOnInit(){
        this._cartService.currentCount.subscribe(count => this.count = count);
    }
    newCount() : number{
        return this._cartService.changeCount(this.count + 1)
    }
}

ProductList 组件 HTML:

<button (click)='newCount()'><i class="fa fa-shopping-cart">{{count}}</i></button>

导航组件:

export class NavComponent implements OnInit {

  count : number;

  constructor(private _cartService : CartService){}

  ngOnInit(){
    this._cartService.currentCount.subscribe(count => this.count = count);
    console.log('count in Nav Component :: '+this.count);
  }

}

NavComponent HTML :

<a class="nav-link">Cart ( <i class="fa fa-shopping-cart"> {{count}} </i> )</a>

NavComponent HTML 中的计数始终显示为 0。请帮助

这是因为您是 re-providing ProductListComponent 中的 CartService...因此获得了与全局实例不同的实例。 只需将其从 ProductListComponent 中的提供程序中删除即可。

顺便说一句:您可以查看注入器树的文档,并且在使用可观察对象时,您还应该查看 ChangeDetection 策略(在您的情况下 OnPush 会更好)。 还使用类似的东西:

// in nav.component.ts
count$: Observable<number>
...

this.count$ = this._cartService.currentCount
...

// in nav.component.html
...
{{count$ | async}}
...

```

会更加地道并为您处理取消订阅和更改检测。