【问题标题】:Calling a method on a cast Typescript class在强制转换 Typescript 类上调用方法
【发布时间】:2019-05-03 22:42:42
【问题描述】:

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

contact.ts

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

  getFullname() {
    return this.firstname + this.lastname
  }
}

contact.service.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$;
  }
}

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;
      })
    })
  }
}

component.component.html

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

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

TypeError: _v.context.$implicit.getFullname 不是函数

如果有办法在强制转换对象上调用函数,有人能解释一下为什么会这样吗?

【问题讨论】:

    标签: angular typescript firebase google-cloud-firestore


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢道格。我完全不了解这里。感谢您的帮助。
    • 知道出了什么问题,我最终在这里寻找一个好的解决方案。 Object.assign() 似乎是最佳实践解决方案。对于类似的用例,有些人更喜欢对象传播(请参阅stackoverflow.com/questions/32925460/…
    猜你喜欢
    • 2016-01-06
    • 2018-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多