【问题标题】:Observable value is not updating可观察值未更新
【发布时间】:2018-07-27 14:40:26
【问题描述】:

我正在尝试使用 Angular 中的一项服务,该服务将应用程序的状态保存在一个字符串变量中。我正在使用 RxJS 来使用 BehaviorSubject,然后我的组件订阅了 BehaviorSubject 的 observable。

State.Service.ts

import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Injectable } from '@angular/core';


@Injectable()
export class StateService {

  private sourceState = new BehaviorSubject<string>('Default State');
  currentState = this.sourceState.asObservable();

  constructor() { }

  setState(state: string) {
    this.sourceState.next(state);
    console.log(this.currentState);
    }
}

我的组件在 NgOnInit 生命周期中都订阅了这个 observable。

Nav.component.ts

import { Component, OnInit } from '@angular/core';
import { AuthService } from '../../services/auth.service';
import { StateService } from '../../services/state.service';
import { Router } from '@angular/router';
import 'rxjs/add/operator/filter';
import { Location } from '@angular/common';

@Component ({
  selector: 'app-nav',
  templateUrl: './nav.component.html',
  styleUrls: ['./nav.component.scss'],
  providers: [StateService]
})
export class NavComponent implements OnInit {
  currentState: string;

  constructor(
    private authService: AuthService,
    private router: Router,
    private stateService: StateService
  ) {}

  ngOnInit() {
    this.stateService.currentState.subscribe(
      state => (this.currentState = state)
    );
  }

  logout() {
    this.authService.logout();
  }
  
  changeState(state: string) {
    this.stateService.setState(state);
  }
}

我的应用程序中的其他组件将调用 state.service.ts 文件中的 setState 函数。我在模板中绑定状态值只是为了观察值,这样我就可以使用指令来根据应用程序状态更改体验。

问题

即使当我 console.log 可以看到它被正确设置时,组件中的值也没有改变。

注意

当我在导航组件中调用 setState 函数时,我确实看到字符串插值的值发生了变化,但仅在 nav.component.ts 中,其他组件不会改变。这几乎就像他们在使用 observable 的克隆。

nav.component.html

<nav class="navbar" [ngClass]="{red: currentState==='stove'}">
  <a  class="navbar-brand" routerLink="/app">
    <img src="../assets/img/app/back.svg" alt="">
  </a>
  <ul class="nav justify-content-end">
    <li class="nav-item">
      <a class="nav-link active" routerLink="/login" (click)="logout()">Logout
        <i class="fa fa-sign-out" aria-hidden="true"></i>
      </a>
    </li>
  </ul>
</nav>
{{ currentState }}

【问题讨论】:

标签: angular typescript rxjs observable


【解决方案1】:

问题与此有关,

@Component ({
  selector: 'app-nav',
  templateUrl: './nav.component.html',
  styleUrls: ['./nav.component.scss'],
  providers: [StateService]
})

您在组件中提供服务,这意味着您没有获得它的单例实例。检查这个相关的answer

您必须使用 NgModule 提供程序数组,并将其从组件的数组提供程序中删除。

@NgModule({
  ...
  providers: [StateService],
  ...
}) 

【讨论】:

    猜你喜欢
    • 2021-06-15
    • 2021-10-26
    • 2016-11-26
    • 1970-01-01
    • 2020-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多