我正在尝试使用包含BehaviorSubject
的RxJS boolean
,该BehaviorSubject
表示用户是否已在应用程序中连接/登录。
这是在用户通过身份验证后订阅新true
值即 BehaviorSubject
的组件:
import {Component, OnInit} from '@angular/core';
import {CollapseDirective} from 'ng2-bootstrap';
import {PublicNavbarComponent} from './public.navbar.component';
import {PrivateNavbarComponent} from './private.navbar.component';
import {SessionService} from '../../session/session.service';
@Component({
selector: 'navbar',
templateUrl: 'app/shared/components/navbar.component.html',
providers: [SessionService],
directives: [PublicNavbarComponent, PrivateNavbarComponent, CollapseDirective]
})
export class NavbarComponent implements OnInit {
constructor(private sessionService:SessionService) {
}
ngOnInit() {
this.sessionService.authenticated$.subscribe({
next: (value)=> this.isAuthenticated = value
});
}
isAuthenticated:boolean = false;
isCollapsed:boolean = true;
}
这是包含
authenticated$
的类/服务:import {Injectable} from '@angular/core';
import {Http, Headers, RequestOptions} from '@angular/http';
import {Credentials} from '../shared/models/credentials.model';
import {BehaviorSubject} from 'rxjs/BehaviorSubject';
import 'rxjs/Rx';
@Injectable()
export class SessionService {
authenticated$:BehaviorSubject<boolean> = new BehaviorSubject(false);
currentUserAccount;
constructor(private http:Http) {
}
signin(credentials:Credentials) {
let headers = new Headers({'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'});
let options = new RequestOptions({headers: headers});
this.http.post('/api/signin', 'username=' + credentials.username + '&password=' + credentials.password, options)
.subscribe(response=>
this.setPersonalInfo(response.headers.get('x-auth-token'))
);
}
setPersonalInfo(sessionToken) {
localStorage.setItem('authenticated', 'true');
localStorage.setItem('sessionToken', sessionToken);
this.authenticated$.next(true);//next() from false to true
this.http.get('/api/utils/current-useraccount')
.subscribe(param => this.currentUserAccount = param);
}
}
但是,这没有预期的行为: session 服务中的
setPersonalInfo
似乎仅在isAuthenticated
函数中为true,而调用NavbarComponent
时根本没有通知this.authenticated$.next(true)
的ojit_code。 最佳答案
似乎您有SessionService
的多个实例。例如您提供了多次,并且您在其中调用signin
的实例与您在NavbarComponent
中注入(inject)的实例不同。
如何提供服务取决于您的项目设计。通常, session 服务为单例。
我建议从providers: [SessionService],
中删除NavbarComponent
。
关于typescript - RxJs BehaviorSubject的订户未收到有关值更改的通知的问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37150891/