Search code examples
angularfirebaseangularfire2google-cloud-firestoreangularfire5

Angular & AngularFire 5 Retrieve Data From Document


What I'm Using

  • Angular 5
  • AngularFire5
  • Firebase & Firestore

What I'm Trying to Achieve

I am currently using Google Firebase's new Firestore to create a new app while learning angular. My app currently creates a collection called Links and creates a new document with a custom id that is generated when the user adds a link and is the shorturl, and in that document, there are 4 fields:

  • uid
  • url
  • shorturl
  • clicks

I want the app to query the data that is within the document in the url field.

What I have So Far

I've created a path to the correct document:

  linkCollection: Observable<{}>;
  constructor(private afs: AngularFirestore, private router: Router) {
      this.path = this.router.url.replace('/','');
      afs.collection('Links').doc(this.path).valueChanges();
  }

Where I'm Stuck

This is probably an easy solution but im not sure how to get the url field. The code I have is able to retrieve the document and I use a similar method in another section to retrieve all of the thinks and using *ngFor display the data but im not sure how to do it in the ts file instead of the template.


Solution

  • Here's the basic pattern you would follow to read a document as an Observable and use its data in a component template.

      linkRef: AngularFirestoreDocument<any>;
      link: Observable<any>;
      path: string;
    
      constructor(private afs: AngularFirestore, private router: Router) {}
    
      ngOnInit() {
        // 0. this works, but there's probably better ways to get the ID
        this.path = this.router.url.replace('/','');
    
        // 1. make a reference
        this.linkRef = this.afs.collection('links').doc(this.path)
    
        // 2. get the Observable
        this.link = this.linkRef.valueChanges();
      }
    

    Then in your HTML, you can unwrap the observable and display the URL property.

    {{ (link | async)?.url }}
    

    Alternatively, can unwrap it by subscribing manually somewhere in the TS, but you should also unsubscribe during NgOnDestroy to avoid memory leaks.

    this.link.subscribe(data => console.log(data) )