Vivek Modi
Vivek Modi

Reputation: 7291

Firestore to get single data from angular

I am new in angular. Please help me to get single data from firestore. I am getting full data from database but I need specific data from the database. This is my code for angular to get Full Data. I have mentioned two files of code first one is service and another one is to display code.

service.ts

import { Injectable } from '@angular/core';
import { AngularFirestore,AngularFirestoreDocument,AngularFirestoreCollection } from '@angular/fire/firestore';
import { User } from '../models/user';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class RegisterService {
  private registerCollection : AngularFirestoreCollection<User>;
  private  resgisters : Observable<User[]>;
  private registerDocu : AngularFirestoreDocument<User>;

  constructor(public db : AngularFirestore) {
    this.registerCollection = db.collection<User>('Register');
    this.resgisters = db.collection('Register').valueChanges();

    this.resgisters = this.registerCollection.snapshotChanges().pipe(
      map(actions => {
        return actions.map(a => {
          const data = a.payload.doc.data();
          const id = a.payload.doc.id;
          return { id, ...data };
        });
      })
    );
    }
    addRegister(user: User) {
       this.registerCollection.add(user);
    }
    getRegister(){
      return this.resgisters;
    }

}

firestore image

Profile.page.ts

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { AuthService } from '../../../services/auth.service';
import { LoggingService } from '../../../services/logging.service';
import { RegisterService } from '../../../services/register.service';
import { User } from '../../../models/user';

import * as firebase from 'firebase/app';

@Component({
  selector: 'app-profile',
  templateUrl: './profile.page.html',
  styleUrls: ['./profile.page.scss'],
})
export class ProfilePage implements OnInit {
  user : User[];

  constructor(private registerservice : RegisterService,private loggingService: LoggingService, private activatedRoute: ActivatedRoute, private authService: AuthService) { }

  ngOnInit() {
    this.registerservice.getRegister().subscribe(register => {
       this.user = register;
       console.log(this.user);
    });      
  } 
}

Upvotes: 3

Views: 4684

Answers (1)

Lucian Moldovan
Lucian Moldovan

Reputation: 587

In order to get a single object from Firestore Database you need to query a Document. Based on your code structure, the getRegister() method should be:

getRegister(node) {
   return this.db.Doc<User>('Register/' + node).valueChanges();
}

You can find documentation on the library github page: https://github.com/angular/angularfire2/blob/master/docs/firestore/documents.md

Upvotes: 1

Related Questions