代码之家  ›  专栏  ›  技术社区  ›  farahm

角度模型getter“不是函数”错误

  •  0
  • farahm  · 技术社区  · 7 年前

    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

    1 回复  |  直到 7 年前
        1
  •  0
  •   Julius Dzidzevičius    7 年前

    将userLoadedFromFirestore类型设置为 User[] 类型,但当数据到达时,它不能保证该对象将是 User

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

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

    this.userLoadedFromFirestore[0].username;

        2
  •  0
  •   Iván Kollár    4 年前

    在我的例子中,解决方案是将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;
        }
    }
    
    推荐文章