javascript - Angular: returning a value from onValue() in firebase realtime database - TagMerge
4Angular: returning a value from onValue() in firebase realtime databaseAngular: returning a value from onValue() in firebase realtime database

Angular: returning a value from onValue() in firebase realtime database

Asked 1 years ago
1
4 answers

When you call onValue you get the current value from that path in the database, and then also get all updates to that value. Since your callback may be called multiple times, there is no way to return a single value.

If you want to just get the value once and return it, you'll want to use get instead of onValue. Then you can also use async/await.

async getLoggedInUser(id: string): Promise<User> {
  const db = getDatabase();
  var user: User;
  const snapshot = await get(ref(db, '/users/' + id))
  user = snapshot.val();
  return user;
}

Source: link

0

@angular/fire provides AngularFireDatabase service that allows us to work with the Realtime Database. It’s an efficient, low-latency solution for apps that require synced states across clients in realtime.
import { AngularFireDatabase} from '@angular/fire/database';
export class TutorialService {
  constructor(private db: AngularFireDatabase) { }
}
– Create an object binding/ Retrieve:
tutorial: AngularFireObject<any>;
// db: AngularFireDatabase
this.tutorial = db.object('tutorial');
 
// or
Observable<any> tutorial = db.object('tutorial').valueChanges();
– Create/Update an object:
const tutRef = db.object('tutorial');
 
// set() for destructive updates
tutRef.set({ title: 'zkoder Tutorial'});
– Update an object:
const tutRef= db.object('tutorial');
tutRef.update({ url: 'bezkoder.com/zkoder-tutorial' });
– Delete an object:
const tutRef = db.object('tutorial');
tutRef.remove();

Source: link

0

davideast feat(core): Upgrade to Firebase v9 & more (#2770) … Latest commit b34b218 Aug 19, 2021 History
* Support Firebase v9
* New API that Zone wraps Firebase JS SDK and rxfire
* AngularFire v6 API lives on at `@angular/fire/compat/*`
* Drop Angular versions less than 12
* Require Ivy
If you've followed the earlier step "Installation and Setup" your /src/app/app.component.ts should look like below.
import { Component } from '@angular/core';
import { AngularFireDatabase } from '@angular/fire/compat/database';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.css']
})
export class AppComponent {
  items: Observable<any[]>;
  constructor(db: AngularFireDatabase) {
    this.items = db.list('items').valueChanges();
  }
}
Create an object binding
const relative = db.object('item').valueChanges();
Then in your template, you can use the async pipe to unwrap the binding.
import { Component } from '@angular/core';
import { AngularFireDatabase } from '@angular/fire/compat/database';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-root',
  template: `
  <h1>{{ (item | async)?.name }}</h1>
  `,
})
export class AppComponent {
  item: Observable<any>;
  constructor(db: AngularFireDatabase) {
    this.item = db.object('item').valueChanges();
  }
}
The promise can be useful to chain multiple operations, catching possible errors from security rules denials, or for debugging.
const promise = db.object('item').remove();
promise
  .then(_ => console.log('success'))
  .catch(err => console.log(err, 'You dont have access!'));

Source: link

0

5. NOW ADD BELOW CODE INTO YOUR ANGULAR.JSON FILE:
"styles": [              ...              "node_modules/bootstrap/dist/css/bootstrap.min.css",              "node_modules/@fortawesome/fontawesome-free/css/all.css",              "node_modules/ngx-toastr/toastr.css"            ],
6. YOU NEED TO ADD FIREBASE CONFIGURATION THAT I HAVE SHOWN YOU IN ABOVE SECOND VIDEO(CREATE DATABASE ON FIREBASE) AND YOU NEED TO ADD THAT DETAILS IN SRC/ENVIRONMENTS/ENVIRONMENT.TS FILE:
export const environment = {  production: false,    firebaseConfig : {    apiKey: "***",    authDomain: "***",    databaseURL: "***",    projectId: "***",    storageBucket: "***",    messagingSenderId: "***",    appId: "***",    measurementId: "***"  }};
7. NOW ADD OR REPLACE BELOW CODE INTO YOUR APP.MODULE.TS FILE:
import { BrowserModule } from '@angular/platform-browser';import { NgModule } from '@angular/core';import { AngularFireModule } from '@angular/fire';import { AngularFireDatabaseModule } from '@angular/fire/database';import { AngularFirestoreModule } from '@angular/fire/firestore';import { AppComponent } from './app.component';import { environment } from 'src/environments/environment';import { AddStudentComponent } from './add-student/add-student.component';import { StudentListComponent } from './student-list/student-list.component';import { EditStudentComponent } from './edit-student/edit-student.component';import { FormsModule, ReactiveFormsModule } from '@angular/forms';import { BrowserAnimationsModule } from '@angular/platform-browser/animations';// NGX Paginationimport { NgxPaginationModule } from 'ngx-pagination';import { ToastrModule } from 'ngx-toastr';import { RouterModule, Routes } from '@angular/router';// Routes array define component along with the path name for urlconst routes: Routes = [  { path: '', redirectTo: '/register-student', pathMatch: 'full' },  { path: 'register-student', component: AddStudentComponent },  { path: 'view-students', component: StudentListComponent },  { path: 'edit-student/:id', component: EditStudentComponent }];@NgModule({  declarations: [    AppComponent,    AddStudentComponent,    EditStudentComponent,    StudentListComponent  ],  imports: [    BrowserModule,    FormsModule,    ReactiveFormsModule,        AngularFireModule.initializeApp(environment.firebaseConfig),    AngularFireDatabaseModule,    AngularFirestoreModule,    BrowserAnimationsModule, // required animations module    NgxPaginationModule,    ToastrModule.forRoot(),    RouterModule.forRoot(routes)  ],  providers: [],  bootstrap: [AppComponent]})export class AppModule { }
8. NOW ADD BELOW CODE INTO YOUR APP.COMPONENT.HTML FILE:
<!-- Top navigation --><nav class="navbar navbar-dark fixed-top bg-dark flex-md-nowrap p-0 shadow">  <a class="navbar-brand col-sm-3 col-md-2 mr-0" routerLink="/register-student">        <span class="dasboard-text">Therichpost</span>  </a>  <ul class="navbar-nav px-3">    <li class="nav-item text-nowrap">      <a class="nav-link" routerLink="/register-student">        <span class="user-image" style="background-image: url('assets/user.jpg')"></span>        Hello Ajay      </a>    </li>  </ul></nav><!-- Sidebar navigation --><div class="container-fluid">  <div class="row">    <nav class="col-md-2 d-md-block bg-light sidebar" style="margin-top: 70px;">      <div class="sidebar-sticky">        <ul class="nav flex-column">          <!-- routerLink="/register-student" to navigate to view-students component -->          <li class="nav-item">            <a class="nav-link" routerLink="/register-student" routerLinkActive="active">              <i class="fas fa-plus">Add Student            </a>          </li>          <!-- routerLink="/view-students" to navigate to view-students component -->          <!-- routerLinkActive="active" activates active class for component-->          <li class="nav-item">            <a class="nav-link" routerLink="/view-students" routerLinkActive="active">              <i class="fas fa-list-ul">Students List            </a>          </li>        </ul>      </div>    </nav>    <!-- Main content -->    <main role="main" style="margin-top: 50px;" class="col-md-9 ml-sm-auto col-lg-10 px-4">      <div class="inner-adjust">        <!-- Use router template to show the components for which router service is activated -->        <router-outlet></router-outlet>      </div>    </main>  </div></div>
9. FIRST CREATE SERVICES FOLDER INTO YOUR APP FOLDER AND RUN BELOW COMMAND:
ng g s services/crud

Source: link

Recent Questions on javascript

    Programming Languages