首页 > 解决方案 > 角度模型吸气剂“不是函数”错误

问题描述

我的模型:

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 在编译过程中没有显示任何错误...

标签: angularfunctionmodelgoogle-cloud-firestore

解决方案


您将 userLoadedFromFirestore 的类型设置为User[]类型,但是当数据到达时,并不能保证该对象将是一个User类型。这就是为什么设置传入数据的类型是个好主意:

subscribe(((item: User[]) => {

在您的情况下,您很可能需要:

this.userLoadedFromFirestore[0].username;


推荐阅读