angular - 如何在 Angular 2 的不同服务中订阅可观察对象

标签 angular rxjs

我有一项服务,可以简单说明用户是否登录。 它从另一个服务更新,该服务执行 http 请求以验证用户。

我想要一个导航栏组件来更新用户界面,以根据可观察对象 (BehaviorSubject) 向用户显示登录或注销按钮。

(在我的 Bootstrap 函数中,我正在注入(inject) 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);     
    }
}

登录服务.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);
}

最佳答案

@Inject(Auth) _auth 看起来已经成功了。

nav-main.component.ts

import {Component, OnInit, Inject} from 'angular2/core';

_auth;

constructor(public _router: Router,
            public _service: IsActiveRouteService,
            @Inject(Auth) _auth){

    this._auth = _auth;//@Inject(Auth) _auth did the trick
}

ngOnInit() {
    this._auth.check()
                .subscribe(data =>{
                    console.log('nav init check() '+data)
    });
}

auth.service.ts

import {Injectable} from 'angular2/core';
import {Observable} from "rxjs/Observable";
import {Subject} from 'rxjs/Subject';
import {BehaviorSubject} from 'rxjs/Rx';


@Injectable()

export class Auth {
    isLoggedIn:boolean = false;
    logIn$: Subject<boolean> = new BehaviorSubject<boolean>(this.isLoggedIn);
    externalBS;

    constructor() {
        this.logIn$.asObservable();
        this.externalBS = this.logIn$;
    }


    login(id_token) {
        window.localStorage.setItem('id_token',id_token);
        this.isLoggedIn = true;
        this.logIn$.next(this.isLoggedIn);
    }


    logout() {
        window.localStorage.setItem('id_token','');
        this.isLoggedIn = false;            
    }

    check() {
        return this.externalBS.asObservable().startWith(this.isLoggedIn);
    }

}

关于angular - 如何在 Angular 2 的不同服务中订阅可观察对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37329056/

相关文章:

angular - 在 Material 工具提示中添加 href

angular - Cypress 仍停留在 Chrome stable 80 上

drag-and-drop - RXJS 拖放

angular - RxJS Observable with Subject,通过计时器轮询和 combineLatest 不会触发

javascript - Observables 中的 Promise.all 等价物是什么?

angular - 将列和数据动态加载到 Angular 2 中的表中

angular - 如何将我自己的 RxJS 主题双向绑定(bind)到 [(ngModel)]?

Angular:将模板传递给子组件的最佳/推荐方式

ajax - 如何在 RXJS5 中正确发出 Observable.ajax.post 请求

Angular 6 Async-await 无法处理 http 请求