【发布时间】: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