我能够在我的componentsnet2中获得'0'值,但不能得到this.navItem $在UserService下的下一个值
`import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
@Injectable()
export class UserService {
constructor() {}
// Observable navItem source
public _navItemSource = new BehaviorSubject(0);
// Observable navItem stream
navItem$ = this._navItemSource.asObservable();
// service command
changeNav(number) {
this._navItemSource.next(number);
console.log(this._navItemSource.getValue())
console.log(this.navItem$)
}
}`
我使用的服务如下
`export class Component1{
constructor(private _userService: UserService)
fun(){
this._userService.changeNav(this.notificationslist)
}
}`
在我的另一个组件中,我想检查服务中的值
` export class Component2{
ngOnInit() {
this.subscription = this._userService.navItem$
.subscribe(item => this.item1 = item)
console.log(this.subscription)
console.log(this.item1)
}
}`
我的问题是当我订阅时,我在控制台上获得以下数据
我只得到初始值'0'但不是下一个更改的值,
如何检查数组中的最后一个值或特定值,从每个我打开component2的每个时间开始更改为例如"Status:Inprogress"到"Status:Success"因为根据该状态我必须显示并隐藏一些元素
1 回答
我认为这应该是有帮助的,有很多没有 . 对于同一场景的答案,但我们通常不会注意答案的细节,而且我发布的问题与其他人已经面临的问题相同 . 我们不应该在每个组件中使用提供程序:[xyzservice],而应该只在较高的根组件上使用 . 以下链接中已有答案:
Angular2 + RxJS BehaviorSubject subscription not working on all components
Angular2: subscribe to BehaviorSubject not working
Angular2 Observable BehaviorSubject service not working