在类型转换 Typescript 类上调用方法

Chr*_*ton 2 firebase typescript angular google-cloud-firestore

我正在使用 Cloud Firestore 投射到一个工作正常的对象。但是,我似乎无法在该对象上调用方法。这是我的模型定义 -

联系人.ts

export class Contact {
  id: string
  firstname: string
  lastname: string
  email: string

  getFullname() {
    return this.firstname + this.lastname
  }
}
Run Code Online (Sandbox Code Playgroud)

联系服务.ts

@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$;
  }
}
Run Code Online (Sandbox Code Playgroud)

contact.component.ts

@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;
      })
    })
  }
}
Run Code Online (Sandbox Code Playgroud)

组件.component.html

<div *ngFor="let contact in contacts">{{contact.getFullname()}}</div>
Run Code Online (Sandbox Code Playgroud)

但该getFullname()方法只是抛出一个错误

类型错误:_v.context.$implicit.getFullname 不是函数

有人可以解释为什么这是一个 if 有办法在强制转换对象上调用函数吗?

Dou*_*son 5

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

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