我只想说一开始,我正在学习有角度的知识,并且刚开始掌握所有不同的概念。
好的,我的项目已经完成,可以从Firebase数据库中编辑和删除联系人,并且视图将更新。但是当我添加新联系人时,它不会更新。
设置方式如下:
联系服务
getContacts() {
this.http.get<any[]>(firebaseURL + 'contacts.json')
.pipe(
map(response => {
const temp: any[] = [];
for (const identifier in response){
temp[identifier] = response[identifier];
}
return temp;
})
).subscribe(contacts => this.contactSource.next(contacts));
}
addContact(contact: Contact) {
return this.http.post<Contact>(firebaseURL + 'contacts.json', contact);
}
contactEdit(identifier: string, contact: any) {
return this.http.patch<Contact>(firebaseURL + 'contacts/' + `${identifier}.json`, contact);
}
deleteContact(identifier: string) {
return this.http.delete<Contact>(firebaseURL + 'contacts/' + `${identifier}.json`);
}
如果您希望从数据库中更新联系人数组,则会调用 getContacts()
应用程序组件(TypeScript)
ngOnInit(): void {
//this.fetchContacts();
this.contactService.contactGet$.subscribe(contacts => {
this.contacts = contacts;
});
this.contactService.getContacts();
this.contactService.contactEdit$.subscribe(contact => {
this.selectedContact = contact;
});
this.contactService.fetchNew$.subscribe(bool => {
//this.fetchContacts();
});
}
应用程序组件(HTML)
<h1>Contact Manager</h1>
<button class="blue" (click)="openCreator()">Add Contact</button>
<app-contact-list *ngIf = "contacts" [contacts] = "contacts"></app-contact-list>
<app-contact-editor *ngIf="selectedContact != null" [identifier] = "selectedContact" [contact] = "contacts[selectedContact]" (closeEditor) = "closeEditor($event)"></app-contact-editor>
<app-contact-creator *ngIf="createContact" (closeCreator) = "closeCreator($event)"></app-contact-creator>
联系人编辑器(TypeScript)-工作(稍后更新视图)
saveChanges() {
let temp: any = {};
if (this.firstName != null && this.firstName.length > 0){
temp.firstName = this.firstName;
}
if (this.lastName != null && this.lastName.length > 0){
temp.lastName = this.lastName;
}
if (this.phone != null && (this.phone + '').length === 10){
temp.phone = this.phone;
}
if (this.email != null && this.email.length > 0){
temp.email = this.email;
}
if (temp != null){
this.contactService.contactEdit(this.identifier, temp)
.subscribe(() => {
this.contactService.getContacts();
this.close();
});
}
}
Contact Creator(TypeScript)-不起作用(以后不更新视图)
create() {
let temp: Contact = { firstName: this.firstName, lastName: this.lastName, phone: this.phone, email: this.email };
this.contactService.addContact(temp)
.subscribe(() => {
this.contactService.getContacts();
this.close();
});
}