【问题标题】:BehaviorSubject keeps resetting to original valueBehaviorSubject 不断重置为原始值
【发布时间】:2023-03-26 11:00:02
【问题描述】:

我有一个 angular 2 项目,其中有几个组件。 其中一个组件使用订阅跟踪成员(即前面提到的 BehaviorSubject)。

当用户单击按钮时,BehaviorSubject 的值会更新并推送。

但是,在订阅时,唯一推送的值是原始值(即 0)。

Navbar 组件是订阅者,在 CountService 中声明了 BehaviorSubject。

我的计数服务:

@Injectable()
export class CountService {
    private count:number;
    public countObservable:BehaviorSubject<number>;
    public savedItems = { campaigns: [], news: [] };

    constructor (private http: Http) {
        this.count=0;
        this.countObservable = new BehaviorSubject<number>(this.count);
        this.countObservable.next(this.count);
    }

    keep(keepId: string, type: string){
        !!this.savedItems[type].length ?
            this.savedItems[type].find(i => i == keepId).length ?
            console.log('exist') : this.keepInSavedItems(keepId, type)
            this.keepInSavedItems(keepId, type);
    }

    keepInSavedItems(keepId, type){
        this.savedItems[type].push(keepId);
        this.count++;
        this.countObservable.next(this.count);
    }
}

我的导航栏组件:

@Component({
  selector: 'navbar',
  templateUrl: './navbar.component.html',
  providers: [ CountService ]
})
export class NavigationbarComponent implements OnInit {
  count:number;

  constructor(public countService: CountService){
    this.count=0;
  }

  ngOnInit() : void {
    this.countService.countObservable.subscribe( count => this.count=count);
  }
}

【问题讨论】:

  • 你如何通知推送值,即你的点击方法是什么样的?
  • 我实际上设法通过将 observable 设为静态来解决它。

标签: angular rxjs observable behaviorsubject


【解决方案1】:

当您在组件中提供服务时,您将为每个NavigationbarComponent 获得一个新的CountService 实例。 如果组件是由路由器添加的,则每次路由更改都可能会破坏并重新创建组件和服务。

如果您只在 @NgModule() 中提供服务(仅非延迟加载的模块),那么您的整个应用程序将只有一个实例。

【讨论】:

  • 做到了,现在计数确实更新了,但值并没有用 countObservable.next(this.count) 推送
【解决方案2】:

这可能是因为各个组件中使用了 providers 数组。

从各个组件中移除 provides:[CountService] 并在 rootcomponent's @NgModule

中声明

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-20
    • 1970-01-01
    • 2017-08-07
    • 2020-10-29
    相关资源
    最近更新 更多