我为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.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
})
}
为什么返回所需和期望值,但未将其分配给组件变量?
答案 0 :(得分:0)
您何时设置setCurrent
?如果您在订阅之前执行此操作,则不会获得当前值。您可以尝试将其更改为BehaviorSubject
而不是Subject
。