1

I have documents of users with first name and last name separated. I need access to them in the component and then merge them so I can save the whole name in another collection. So far I have only found broken or deprecated code from obsolete versions. https://github.com/angular/angularfire2/blob/master/docs/firestore/documents.md And with this code I don't get access in the component. How do I store the values in variables in the component so I can use them?

export interface user {
 first_name: string;
 last_name: string;
}
export class UserComponent {

 userCollection: AngularFirestoreCollection<user>;
 firstname: string;
 lastname: string;

 constructor(private afs: AngularFirestore) {
    this.userCollection.doc(this.user).ref.get().then(function(doc) {
    console.log(doc.data());
    *MISSING CODE*
    console.log(this.firstname, this.lastname);
  }
 }

Which .get or .ref or payload or doc.data() or .pipe do I have to use now to save the data from firebase in those 2 variables "firstname" and "lastname" so I can work with them in the component? I get the whole object in the console, but not each variable separated. It took me 4 days to find out that ".get()" on FirestoreCollections only works when I put a ".ref" in front of it, if anyone could help me to find this information faster, that would be very appreciated.

2
  • Please show the result of console.log(doc.data()) Commented Dec 1, 2018 at 23:09
  • Then I get the object: Document data: {first_name: "John", last_name: "Doe", …} first_name: "John" last_name: "Doe" proto: Object Commented Dec 2, 2018 at 4:35

1 Answer 1

1

Since tou are getting the data, you could just assign it as follows,

 constructor(private afs: AngularFirestore) {
    this.userCollection.doc(this.user).ref.get().then(function(doc) {
    this.firstname = doc.data().first_name;
    this.lastname = doc.data().last_name;    
    console.log(this.firstname, this.lastname);
}
Sign up to request clarification or add additional context in comments.

1 Comment

"Uncaught (in promise): TypeError: Cannot set property 'firstname' of undefined TypeError: Cannot set property 'firstname' of undefined" But it is right below the userCollection.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.