【发布时间】: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 }}
【问题讨论】:
-
可能与您的问题有关,stackoverflow.com/questions/36919399/…
标签: angular typescript rxjs observable