简体   繁体   中英

Firebase Promise Error with Observable/BehaviorSubject

Angular Firebase: I have a function that sets a value to photon2 . I need to get this value out of my getPhoton() function and into my Observable BehaviorSubject isLoginSubject ? I get an error:

ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'isLoginSubject' of undefined

Here is my auth-service.ts code I would appreciate any help!

  import { Injectable } from '@angular/core';
  import { Router } from '@angular/router';
  import { AngularFireAuth } from 'angularfire2/auth';
  import { AngularFireList, AngularFireDatabase, AngularFireObject, >AngularFireAction } from 'angularfire2/database';
  import * as firebase from 'firebase/app';
  import { Observable } from 'rxjs/Observable';
  import { ProgramService } from '../views/shared/program.service';
  import { BehaviorSubject } from 'rxjs/BehaviorSubject';

  @Injectable()
  export class AuthService {
    _photon: string;
    isLoginSubject = new BehaviorSubject<string>(this._photon);
    public user: Observable<firebase.User>;
    itemRef: AngularFireObject<any>;
    public userDetails: firebase.User = null;
    public LOGGEDIN: boolean = null;

    ownersRef = firebase.database().ref().child('owners');

    constructor(private _firebaseAuth: AngularFireAuth, private router: >Router, private programService: ProgramService,
                private db: AngularFireDatabase) {

      this.user = _firebaseAuth.authState;
      this.user.subscribe(
        (user) => {
          if (user) {
            this.getPhoton(user); // I would like to use this function with >an Observable/BehaviorSubject.
            this.userDetails = user;
            this.getController(this.userDetails.uid); // I don't want to use >the localStorage approach... but it works!
            this.LOGGEDIN = true;
          } else {
            this.userDetails = null;
          }
        }
      );
    }

  getPhoton(user) {
  // retrieves "controller" name from the logged in firebase user. How can I >push that to an Observable/BehaviorSubject
    if (user) {
      this.ownersRef.orderByChild('userId').equalTo(user.uid).once('value')
      .then((snap) => {
        snap.forEach(function(data) {
        const photon2 = data.val().controller;  // QUESTION: How do I make >this an Observable-BehaviorSubject?
        console.log('getPhoton controller: ' + photon2);
        this.isLoginSubject.next(photon2);  // Error: Uncaught (in promise): >TypeError: Cannot set property '_controller' of undefined
        });
      });
    }
  }

I figured it out and wanted to post the solution for other beginners grasping async concepts! I had to change 1 line snap.forEach(function (data) { to snap.forEach(data => { and now my error is gone and I can .next() the value of photon2 into my BehaviorSubject. Here's the full getPhoton() function from my auth-service.ts file and below that, I'll show how I subscribe to the subject from other components

  getPhoton(user) {
  // retrieves "controller" name from the logged in firebase user that is "next'ed" to an Observable/BehaviorSubject
    if (user) {
      this.ownersRef.orderByChild('userId').equalTo(user.uid).once('value')
      .then((snap) => {
        snap.forEach(data => {
        const photon2 = data.val().controller;
        this.isLoginSubject.next(photon2);
        });
      });
    }
  }

and now from any component, I can call:

ngOnInit() {

  this.authService.isLoginSubject.subscribe((controller) => {
    console.log('holy grail: ' + controller);
  });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM