【问题标题】:To check for the desired value when using Rxjs BehaviorSubject in Angular2在 Angular2 中使用 Rxjs BehaviorSubject 时检查所需的值
【发布时间】:2017-09-08 09:15:36
【问题描述】:

我能够在我的 componenet2 中获得“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”,但没有得到下一个更改的值,
我如何检查数组中的最后一个值或特定值,该值已从例如“状态:正在进行”更改为“状态:成功”,每次我打开组件 2,因为根据该状态,我必须显示和隐藏一些元素

【问题讨论】:

    标签: angular rxjs angular2-services angular2-observables


    【解决方案1】:

    我认为这应该会有所帮助,有很多没有。相同场景的答案,但我们通常不关注答案的细节,我发布的问题与其他人已经面临的问题相同。 我们不应该在每个组件中使用 providers: [xyzservice] ,而应该只在更高的根组件上使用。 下面的链接中已经有答案了:

    Angular2 + RxJS BehaviorSubject subscription not working on all components

    Angular2: subscribe to BehaviorSubject not working

    Angular2 Observable BehaviorSubject service not working

    【讨论】:

      猜你喜欢
      • 2017-05-04
      • 2017-01-22
      • 2023-01-09
      • 1970-01-01
      • 2020-09-27
      • 2017-11-18
      • 2018-07-28
      • 1970-01-01
      • 2021-04-19
      相关资源
      最近更新 更多