angular - 角度模型吸气剂“不是函数”错误
问题描述
我的模型:
export class User {
public username: string;
private email: string;
constructor() {
this.username = undefined;
this.email = undefined;
}
public getUsername(): string {
return this.username;
}
在我看来,我有:
import {User} from '../../models/usermodel';
export classs ... {
user: Observable<User | null>
userCollection: AngularFirestoreCollection<User>;
userLoadedFromFirestore: User[];
this.userCollection = this.afs.collection('users', ref => ref.where('email', '==', this.sessionData.getUser().getEmail()));
this.userCollection.valueChanges().subscribe((item => {
this.userLoadedFromFirestore = item;
this.userLoadedFromFirestore[0].getUsername();
为了访问getUsername()
我得到运行时错误:is not a function
。这是为什么?当我这样做时this.userLoadedFromFirestore[0].username
,它起作用了!
IDE 在编译过程中没有显示任何错误...
解决方案
您将 userLoadedFromFirestore 的类型设置为User[]
类型,但是当数据到达时,并不能保证该对象将是一个User
类型。这就是为什么设置传入数据的类型是个好主意:
subscribe(((item: User[]) => {
在您的情况下,您很可能需要:
this.userLoadedFromFirestore[0].username;
推荐阅读
- sql - 寻找一些 SQL 帮助我有一个我想从中提取的列并且无法为其创建选择任何建议都会有所帮助
- project-reactor - 项目反应堆:将两个单声道相加
无阻塞 - python - 如何确保 GEKKO 中的 Step Function Control 以及对 MV_TYPE 的混淆
- r - 在 R 中将 ASCII 规范化为 UTF-8
- sql - Postgres:每个事件的会话持续时间(行)
- python - 整数序列的高效块引导
- google-chrome - 使用 PDF 文件输入的 Chrome Headless print-to-pdf
- python - 如何在matlab中使用python进行模型预测
- sql - 根据每条记录的最近日期连接表
- sharepoint - SharePoint 2016 补丁建议