【发布时间】:2023-03-08 20:56:02
【问题描述】:
我有一项服务可以简单地说明用户是否登录。 它是从另一个执行 http 请求以验证用户的服务更新的。
我想要一个导航栏组件来更新用户界面,以根据可观察的 (BehaviorSubject) 向用户显示登录或注销按钮。
(在我的引导函数中,我正在注入 Auth)
nav-main.component.ts
import {Auth} from '../services/auth.service';
constructor ( public _auth: Auth) {
this._auth.check().subscribe(data =>{console.log(data)})
}
auth.service.ts
@Injectable()
export class Auth {
subject: Subject<boolean> = new BehaviorSubject<boolean>(null);
loggedIn:boolean = false;
constructor(){
this.subject.next(this.loggedIn);
}
login(id_token){
...
this.loggedIn = true;
this.subject.next(this.loggedIn);
}
check() {
return this.subject.asObservable().startWith(this.loggedIn);
}
}
login.service.ts
import {Injectable, Injector} from 'angular2/core';
import {Http,Headers} from 'angular2/http';
import {AppInjectorService} from './app-injector.service';
import {Auth} from './auth.service';
import {UserService} from './user.service'
import 'rxjs/Rx';
import {Observable} from 'rxjs/Observable';
@Injectable()
export class LogInUserService {
auth:Auth;
injector:Injector;
constructor(private http:Http) {
// let injector: Injector= AppInjectorService();
this.injector = Injector.resolveAndCreate([Auth]);
this.auth = this.injector.get(Auth);
}
logInUser(data) {
...
return this.http.post(this._authUrl, body, { headers:headers})
.map(function(res){ return <UserService> res.json().data;})
.do(data => this.logIn(data))
.catch(this.handleError);
}
//on success tell the auth.login the public key
logIn(data){
this.auth.login(data.publicKey);
}
【问题讨论】: