【发布时间】:2021-04-06 11:35:04
【问题描述】:
我目前正在使用 Angular、NgRx 和 angular fire 编写应用程序。我已经设法获取数据并且可以控制台记录返回对象的数据,但是,我无法访问对象数据
我将数据存储在用户模型中
export interface User {
userID: string;
email: string;
firstname: string;
lastname: string;
}
然后在返回数据的组件中,我创建一个可观察对象并在 ngOnInit 中填充它
currentUser$:Observable<User>;
...
ngOnInit(): void {
this.currentUser$ = this.store.select(fromRoot.getUserDetails);
this.currentUser$.subscribe(user => {
console.log(user)
})
}
这会在控制台中返回
{userID: "xjZ1aqcPFDOAMappYHgMqcYjQie2", email: "jonathansiberry@gmail.com", firstname: "Jonathan", lastname: "Siberry"}
email: "jonathansiberry@gmail.com"
firstname: "Jonathan"
lastname: "Siberry"
userID: "xjZ1aqcPFDOAMappYHgMqcYjQie2"
但是当它改为
console.log(user.firstname)
我看到了错误
core.js:6162 ERROR TypeError: Cannot read property 'firstname' of null
at SafeSubscriber._next (header.component.ts:37)
at SafeSubscriber.__tryOrUnsub (Subscriber.js:183)
at SafeSubscriber.next (Subscriber.js:122)
at Subscriber._next (Subscriber.js:72)
at Subscriber.next (Subscriber.js:49)
at DistinctUntilChangedSubscriber._next (distinctUntilChanged.js:50)
at DistinctUntilChangedSubscriber.next (Subscriber.js:49)
at MapSubscriber._next (map.js:35)
at MapSubscriber.next (Subscriber.js:49)
at MapSubscriber._next (map.js:35)
我尝试使用 JSON 进行解析,但由于订阅中的用户是 User 类型,因此无法转换为字符串
为什么我不能访问用户对象中的值?
【问题讨论】: