Angular 订阅主题';不赋值
我有getter和setter服务:Angular 订阅主题';不赋值,angular,rxjs,Angular,Rxjs,我有getter和setter服务: // Service import { Subject } from 'rxjs'; export class MyService { public currentUser: any = new Subject(); ... there is a function where I call setCurrent and assign value set setCurrent(data: any) { this.currentUser
// Service
import { Subject } from 'rxjs';
export class MyService {
public currentUser: any = new Subject();
... there is a function where I call setCurrent and assign value
set setCurrent(data: any) {
this.currentUser.next(data);
this._localStorage.set('user', JSON.stringify(data))
}
get setCurrent() {
return this._localStorage.get('user');
}
}
在我的组件中,我订阅了currentUser
:
// Component
public user: User;
constructor(
public authService: AuthService,
) {
this.authService.currentUser.subscribe(nextData => {
this.user = nextData;
console.log(nextData) // Expected value, it's here
console.log(this.user) // Undefined
})
}
为什么它是需要的返回值和期望值,但没有将其分配给组件变量?何时设置
setCurrent
?如果在订阅之前执行此操作,则不会获得当前值。您可以尝试将其更改为行为主题
,而不是主题
何时设置setCurrent
?如果在订阅之前执行此操作,则不会获得当前值。您可以尝试将其更改为行为主体
而不是主体
,如果它是一个对象,您可以尝试从lodash使用object.assign或deepClone
,如果它是一个对象,您可以从lodash尝试使用object.assign或deepClone