After diving into the resources provided by Angular.io and the Git Docs for AngularFire2, I decided to experiment with a more efficient approach. It seems that creating a service is recommended when working with the same data across different components in an app. For my project - a small CMS using Angular2/4 and firebase as the database - I started by allowing the admin to modify the CTA (Call to Action) on the home page.
In this setup, the admin can make changes via inputs in the admin panel and save them. The updated text will then be displayed on the home page. Essentially, the home component only needs read access. My question now is: How do I create a service that can be imported by the components using it?
import { Component } from '@angular/core';
import { AngularFireDatabase, FirebaseObjectObservable } from 'angularfire2/database';
@Component({
selector: 'app-root',
template: `
<h1>{{ item | async | json }}</h1>
<input type="text" #newname placeholder="Name" />
<input type="text" #newsize placeholder="Size" />
<br />
<button (click)="save(newname.value)">Set Name</button>
<button (click)="update(newsize.value)">Update Size</button>
<button (click)="delete()">Delete</button>
`,})
export class AppComponent {
item: FirebaseObjectObservable<any>;
constructor(db: AngularFireDatabase) {
this.item = db.object('/item');
}
save(newName: string) {
this.item.set({ name: newName });
}
update(newSize: string) {
this.item.update({ size: newSize });
}
delete() {
this.item.remove();
}
}
The code above directly brings the functionality into the main component. However, it may be more advisable (from my limited knowledge) to use a service that can be injected. I attempted to create one myself but encountered various errors. Any guidance or assistance would be greatly appreciated!