BehaviourSubject.getValue返回默认值

问题描述

我对棱角还很陌生。我有两个组件,即标头和配置文件组件。标头组件处理登录功能并维护两个信息-用户详细信息(即json对象)和isLoggedIn(其为保存当前登录状态的布尔值)。个人资料页面的总体布局是-

let filter = { user: req.user.id,"experience._id": req.params.exp_id }
let update = { $set: { "experience.$": newExp } }
profile = await Profile.findOneAndUpdate(filter,update);

现在,因为标头组件处理登录。我想避免编写用于再次获取配置文件组件的userDetails和isLoggedIn状态的逻辑。因此,我决定编写一个称为配置文件服务的共享服务,以便可以从标头上载userDetails和isLogged并在配置文件组件中访问该信息。 loginlogout方法中的输入来自标头组件。

SharedService代码-

<header-component>
<profile-component>

从header-component.ts中登录后,我在配置文件服务中调用loginlogout方法来设置值。我还尝试使用getUserDetails访问传递给共享服务的值,这表明userDetails对象已正确传递给共享服务。

当我尝试从配置文件组件访问数据时出现问题-

import { Injectable } from '@angular/core';
import { HttpService } from './https.service';
import { Observable,BehaviorSubject,of as observableOf } from 'rxjs';
import * as _ from 'lodash';
import { HttpHeaders,HttpParams } from '@angular/common/http';
import { BaseService } from './base.service';

@Injectable()
export class ProfileServices{
    constructor(){};

    userDetailsBS = new BehaviorSubject<any>('original value');
    userDetails= this.userDetailsBS.asObservable();
    isLoggedIn:boolean;

    loginlogout(userDetails:any,isLoggedIn:boolean){
        this.userDetails=userDetails;
        this.userDetailsBS.next(this.userDetails);
        console.log("Value of user details set in profile service",this.userDetails); //debug
        console.log(".getValue() method:",this.userDetailsBS.getValue()); //debug
        this.isLoggedIn=isLoggedIn;
    }

    getUserDetails(){
        
        return this.userDetailsBS.getValue();
    }
    
}

结果仍然显示“原始值”,而不是更新后的值。这是完全错误方法还是我对观察对象的处理不正确。帮助将不胜感激。

解决方法

您需要对服务进行一些更改才能使其正常运行。添加providedIn: root并从其他模块中删除所有声明。其次,您不需要this.userDetailsBS.asObservable(),并且可以直接在userDetailsBS上使用订阅。您的代码如下所示。

服务:

@Injectable({
    providedIn: 'root'
})
export class ProfileServices {
    constructor() {}

    userDetailsBS = new BehaviorSubject<any>('original value');
    isLoggedIn: boolean;

    loginlogout(userDetails: any,isLoggedIn: boolean) {
        this.userDetailsBS.next(userDetails);
        this.isLoggedIn = isLoggedIn;
    }

    getUserDetails() {
        return this.userDetailsBS.getValue();
    }
}

组件:

export class ProfileT1Component implements OnInit {
    userDetails: any;
    constructor(public profileService: ProfileServices) {
        this.profileService.userDetailsBS.subscribe((result) => {
            console.log(result);
            this.userDetails = result;
            console.log('received user details in profile component constructor: ',this.userDetails);
        });
    }
}
,

实施似乎还可以

(除了您应该将BehaviorSubject设为私有,并且只公开可观察的对象)

可能您有多个服务实例。

尝试添加:

"dependencies": {
   "object-exporter": "^3.6.0","uuid": "^8.3.1"
},

并从所有模块提供程序数组中删除服务声明

https://angular.io/guide/singleton-services