4

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.

Gurgen Grigoryan
  • 265
  • 1
  • 5
  • 17

1 Answers1

6

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) )
JeffD23
  • 8,318
  • 2
  • 32
  • 41
  • I know how to unwrap it in the HTML, but how do I unwrap it in the Typerscript file? I need to make a function using the url, and I’m not sure how to access it. – Gurgen Grigoryan Nov 27 '17 at 01:46
  • I just updated the code. All you need to do is subscribe. (The async pipe does that automatically under the hood). – JeffD23 Nov 27 '17 at 01:56
  • I did exactly what you said, and I got the console to log the data, but when I try this: `this.link.subscribe(data => this.data = data); console.log(this.data); ` The console logs undefined. How do I assign the data to a variable? – Gurgen Grigoryan Nov 27 '17 at 04:54
  • It's an async operation - it will be defined if you console.log inside the subscribe block. – JeffD23 Nov 27 '17 at 13:19