InterviewSolution
| 1. |
How can you connect your Ionic app with FireStore for CRUD operations ? |
|
Answer» Cloud FireStore is a NoSQL Document based database from Firebase. It keeps the data in sync ACROSS client apps through real-time listeners and offers offline support for mobile and web. Using Firestore, we can directly UPDATE data from the app. 1. To use firestore, first create a project on https://firebase.google.com. Then add FireStore to the project. 2. Add the config settings to your ionic app’s environment file as below : export const environment = { production: false, firebase: { apiKey: "your-api-key-goes-here", authDomain: "project.firebaseapp.com", databaseURL: "https://project.firebaseio.com", projectId: "projectid-here", storageBucket: "project.appspot.com", messagingSenderId: "msging-id-here" } };3. Add Firebase and AngularFire2 to your ionic project with this command npm install firebase angularfire2 --save4. create a page and add a service to your project ionic g page pages/categorylist ionic g service services/category5. Import AngularFire and AngularFirestoreModule in your app.module.ts file and add to NgModule import { AngularFireModule } from 'angularfire2'; import { environment } from './../environments/environment'; import { AngularFirestoreModule } from 'angularfire2/firestore'; @NgModule({ declarations: [AppComponent], entryComponents: [], imports: [BrowserModule, IonicModule.forRoot(),FormsModule, HttpClientModule, AppRoutingModule, BrowserAnimationsModule, AngularFireModule.initializeApp(environment.firebase), AngularFirestoreModule], PROVIDERS: [ StatusBar, SplashScreen, { PROVIDE: RouteReuseStrategy, useClass: IonicRouteStrategy } ], bootstrap: [AppComponent] })6. Import AngularFirestore and AngularFirestoreCollection in your service . import { AngularFirestore, AngularFirestoreCollection } from 'angularfire2/firestore';7. Initialize db connection in constructor of service file and fetch data in real time from firestore collection with snapshotChanges() function. Also write a get function to return the output. constructor(private http:HttpClient, db: AngularFirestore) { this.categoryListCollection = db.collection<any>('category'); this.categoryList = this.categoryListCollection.snapshotChanges().pipe( map(actions => { return actions.map(a => { console.log(a.payload.doc.data()); const data = a.payload.doc.data().categoryName; const id = a.payload.doc.id; return {id, data}; }); }) ); } getCategoryList() { return this.categoryList; }8. Now import the service in your page and subscribe to the get function. ngOnInit() { this.expenseService.getCategoryList().subscribe(res => { this.categoryList = res; }); }9. Run a ngFor loop through the recordset in your view to display live data <ion-list> <ion-item *ngFor="let category of categoryList"> {{category.data}} </ion-item> </ion-list> |
|