Home > Mobile >  Angular service returning undefined to component
Angular service returning undefined to component

Time:07-20

I want to pass the return value to my component. I wrote this service using firebase. When calling the geLoggedInUser method in my component it returns undefined. Ideally, I want to pass the doc.id to my component from my service please help;

SERVICE

docId: any;

    
getLoggedInUser() {
    this.fireAuth.onAuthStateChanged((user) => {
      if (user) {
        console.log(user.email, 'user is valid');

        const db = collection(this.firestore, 'users');
        getDocs(db).then((resp) => {
          this.data = [
            ...resp.docs.map((item) => {
              return { ...item.data(), id: item.id };
            }),
          ];

          //filter users array to get current logged in users data
          this.authUser = this.data.filter((item: any) => {
            this.docId = user.uid;
            return item.email === user.email;
          });
        });
      } else {
        this.router.navigate(['/login']);
        return;
      }
    });
    return this.docId;
  }

COMPONENT

  ngOnInit(): void {
    console.log(this.auth.getLoggedInUser());
  }

CodePudding user response:

I recommend get involved in the Promise and Observable concepts. https://firebase.google.com/docs/reference/js/v8/firebase.auth.Auth

Your problem is when you call getLoggedInUser() is doings this:

  1.    return this.docId;
    
  2. Calls this.fireAuth.onAuthStateChanged which returns a Promise, wait and then execute the rest of the response.

What you can do is use an observable variable in the SERVICE and connect to it from the component.

Please read the following Firebase: Should Promise or Observable be used in an Angular project?

I hope this helps!

CodePudding user response:

In angular, when you use services it’s not common to use variable to pass data to components. To that you should use a observables or promises/await/async.

In this case, I would recommend you use a observable. Here you have an example how you can implement it:

docIdSubject =  new BehaviorSubject<any>(null);
Public get docId(){
  return docIdSubject.asObservable();
} 
    
getLoggedInUser() {
    this.fireAuth.onAuthStateChanged((user) => {
      if (user) {
        console.log(user.email, 'user is valid');

        const db = collection(this.firestore, 'users');
        getDocs(db).then((resp) => {
          this.data = [
            ...resp.docs.map((item) => {
              return { ...item.data(), id: item.id };
            }),
          ];

          //filter users array to get current logged in users data
          this.authUser = this.data.filter((item: any) => {
            //this.docId = user.uid
            return item.email === user.email;
         };

         this.docIdSubject.next(user.uid);

        });
      } else {
        this.router.navigate(['/login']);
        return;
      }
    })
  }

ngOnInit(): void {
    this.auth.docId.subscribe(res =>
      console.log(res);
    );
    this.auth.getLoggedInUser();
  }
  • Related