我的模特:
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在编译过程中不显示任何错误...
答案 0 :(得分:0)
您将userLoadedFromFirestore的类型设置为User[]
类型,但是当数据到达时,不能保证该对象将是User
类型。这就是为什么设置传入数据的类型是一个好主意的原因:
subscribe(((item: User[]) => {
根据您的情况,很可能您需要:
this.userLoadedFromFirestore[0].username;
答案 1 :(得分:0)
就我而言,解决方案是在对象之外组织 getter。
export class UserData {
public gid: string;
//Error!
public gidText(): string{
return this.gid;
}
}
解决方案:
export class UserService {
public gidText(): string{
return this.userData.gid;
}
export class UserData {
public gid: string;
}
}