簡體   English   中英

調用BehaviorSubject.next時,Observable.subscribe方法不會觸發

[英]Observable.subscribe method is not triggering when BehaviorSubject.next is called

我試圖獲取用戶是否登錄到我的Navbar組件中,因此我無法/禁用Navbar項目。 我正在使用BehaviorSubject來組播數據。 我的AuthenticationService包含BehaviorSubject對象,如下面的代碼所示:

import {Injectable} from '@angular/core';
import {Http, RequestOptions, Headers} from '@angular/http';
import {LocalStorage, SessionStorage} from "angular2-localstorage/WebStorage";
import {BehaviorSubject} from 'rxjs/BehaviorSubject';

import {Credentials} from './credentials';

@Injectable()
export class AuthenticationService {
    private _baseUrl="http://localhost:8080/webapi/authenticate/";
    private loggedIn: boolean;
    // Observable UserLoggedIn source
    private _userLoggedInBehavior = new BehaviorSubject<boolean>(false);
    // Observable UserLoggedIn stream
    userLoggedInBehaviorStream = this._userLoggedInBehavior.asObservable();

    constructor(private _http: Http){
         this.loggedIn = localStorage.getItem("authToken");
    }

    authenticate(credentials: Credentials){
        return this._http.post(
                            this._baseUrl
                            , JSON.stringify(credentials)
                            , this.getOptions()
                            )
                    .map(res => res.json())
                    .map((res) => {
                        if (res.success) {
                            sessionStorage.setItem("authToken", res.data.token);
                            this.loggedIn = true;
                        }
                        return res.success;
                    });
    }

    logout() {
        sessionStorage.removeItem("authToken");
        this.loggedIn = false;
    }

    isLoggedIn() {
        return this.loggedIn;
    }

    changeUserLoggedInBehavior(loggedIn) {
        this._userLoggedInBehavior.next(loggedIn);
    }

    // This was necessary because api accepts only JSON
    // and if we do not put this header in requests API 
    // responds with 415 wrong media object.
    getOptions(){
        var jsonHeader = new Headers({
            'Content-Type':'application/json'
        });
        var options = new RequestOptions({
            headers: jsonHeader
        });
        return options;
    }
}

我觸發代碼的AuthenticationComponent代碼如下所示:

    import {Component, OnInit, EventEmitter} from '@angular/core';
import {CanDeactivate, Router} from '@angular/router-deprecated';
import {ControlGroup, Control, Validators, FormBuilder} from '@angular/common';

import {AuthenticationService} from './authentication.service';
import {Credentials} from './credentials';
import {EmailValidator} from '../../validators/email-validator';

@Component({
    selector:'auth'
    , templateUrl:'app/components/authentication/authentication.component.html'
    , providers:[AuthenticationService]
})
export class AuthenticationComponent{
    form: ControlGroup;
    title: string = "LogIn";
    credentials: Credentials = new Credentials();

    constructor(
        fb: FormBuilder
        , private _authService: AuthenticationService
        , private _router: Router){

        this.form = fb.group({
            emailId:[
                ''
                , Validators.compose(
                        [
                            Validators.required
                            , EmailValidator.mustBeValidEmail
                        ]
                    )
                ]
            ,password:[
                ''
                , Validators.compose(
                        [
                            Validators.required
                        ]
                    )
            ]
        });
    }

    save(){
        this._authService.authenticate (this.credentials)
                .subscribe((result) => {
                    if (result) {
                        this._authService.changeUserLoggedInBehavior(true);
                        this._router.navigate(['Home']);
                    }
                }); 
    }
}

最后,我的NavbarComponent如下:

import {Component, OnInit, OnDestroy} from '@angular/core';
import {RouterLink} from '@angular/router-deprecated';
import {Subscription} from 'rxjs/Subscription';

import {AuthenticationService} from '../components/authentication/authentication.service';

@Component({
    selector:'navbar'
    , templateUrl: 'app/navbar/navbar.component.html'
    , directives:[RouterLink]
    , providers:[AuthenticationService]
})
export class NavbarComponent implements OnInit, OnDestroy{
    private _isUserLoggedIn: boolean=false;
    subscription: Subscription;
    constructor(
        private _authService: AuthenticationService
    ){}

    ngOnInit(){
        this.subscription = this._authService.userLoggedInBehaviorStream
                                .subscribe(
                                    loggedIn => this._isUserLoggedIn = loggedIn
                                    );
    }

    ngOnDestroy(){
        // prevent memory leak when component is destroyed
        this.subscription.unsubscribe();
    }

    public setUserLoggedId (isLoggedIn: boolean){
        this._isUserLoggedIn = isLoggedIn;
    }
}

以此為例編寫代碼。 請讓我知道我哪里出錯了。

問題是,在兩個組件中,您都在指定提供程序:

providers:[AuthenticationService]

每次在組件中提供一些服務,它都會獲得新的實例。 嘗試在某些父組件中提供AuthenticationService,並注入子組件或引導級別。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM