代码之家  ›  专栏  ›  技术社区  ›  Chris Edgington

在强制转换Typescript类上调用方法

  •  0
  • Chris Edgington  · 技术社区  · 8 年前

    我正在使用CloudFireStore对一个工作正常的对象进行投射。然而,我似乎无法调用该对象上的方法。这是我的模型定义-

    export class Contact {
      id: string
      firstname: string
      lastname: string
      email: string
    
      getFullname() {
        return this.firstname + this.lastname
      }
    }
    

    @Injectable()
    export class ContactService {
      getAll(raiseId: string): Observable<Contact[]> {
        this.contactsCollection = this.afs.collection<IContact>('contacts')
        this.contacts$ = this.contactsCollection.snapshotChanges().pipe(
          map(actions => actions.map(a => {
            const contact = a.payload.doc.data() as Contact;
            const id = a.payload.doc.id;
            return { id, ...contact };
          }))
        );
        return this.contacts$;
      }
    }
    

    @Component({
      selector: 'contact-view',
      templateUrl: './contact-view.component.html',
      styleUrls: ['./contact-view.component.scss']
    })
    export class ContactViewComponent implements OnInit {
      contacts$: Observable<Contact[]>;
      contacts: Contact[];
    
      constructor(
        public contactService: ContactService
      ) { }
    
      ngOnInit() {
          this.contacts$ = this.contactService.getAll();
          this.contacts$.subscribe(contacts => {
            this.contacts = contacts;
          })
        })
      }
    }
    

    component.component.html

    <div *ngFor="let contact in contacts">{{contact.getFullname()}}</div>
    

    但是 getFullname()

    1 回复  |  直到 8 年前
        1
  •  5
  •   Doug Stevenson    8 年前

    您不能简单地将Firestore返回的对象强制转换为任何对象,并假设它可以正常工作。调用data()得到的对象只是一个普通的旧JavaScript对象,其属性与文档的字段匹配。这就是全部。它没有任何方法,将该对象强制转换为其他对象不会为您创建任何方法。强制转换只是改变了TypeScript对该对象的概念,在这种情况下,你只是愚弄了TypeScript,让它认为你有一个Contact实例,而实际上你没有。

    如果要将Firestore数据对象转换为联系人对象,则必须将数据对象的属性复制到新的联系人对象中。一个简单的方法就是使用 Object.assign()

    推荐文章