可观察值未更新

Bro*_*mox 0 observable rxjs typescript angular

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

状态服务

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

我的组件都在NgOnInit生命周期中订阅了此可观察的消息。

导航组件

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);
  }
}
Run Code Online (Sandbox Code Playgroud)

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

问题

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

注意

当我在nav组件中调用setState函数时,确实看到了字符串插值的值更改,但仅在nav.component.ts中,其他组件不会更改。几乎就像他们使用的是可观察的克隆。

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 }}
Run Code Online (Sandbox Code Playgroud)

Lui*_*yfe 5

问题与此有关,

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

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

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

@NgModule({
  ...
  providers: [StateService],
  ...
}) 
Run Code Online (Sandbox Code Playgroud)