Angular2 Firebase承诺

时间:2018-07-31 05:58:15

标签: angular firebase observable angularfire2

我在Angular / Firebase中玩Promises。成功登录后,我将使用登录用户的uid呼叫firebase。我用它来查找在Firebase中分配给他们的用户的“控制器名称”。这样做是为了在snap.val()中返回控制器名称,但是我不知道如何使控制器名称输出在其他组件的其他位置可用。这应该是我的auth.service.ts代码和相应的控制台输出,以显示它正在拉snap.val()的工作,现在我该如何解析它以获取controller的值并使它可观察?在我的整个程序中?

auth.service.ts

import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { AngularFireAuth } from 'angularfire2/auth';
import * as firebase from 'firebase/app';
import { Observable } from 'rxjs/Observable';
import { ProgramService } from '../views/shared/program.service';


@Injectable()
export class AuthService {
  public user: Observable<firebase.User>;
  public userDetails: firebase.User = null;
  public LOGGEDIN: boolean = null;
  private ownersRef: any;

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

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

    this.user = _firebaseAuth.authState;

    this.user.subscribe(
      (user) => {
        if (user) {
          this.userDetails = user;
          console.log(this.userDetails);
          this.getController(this.userDetails.uid);
          this.LOGGEDIN = true;
        } else {
          this.userDetails = null;
        }
      }
    );
  }

  getController(id) {
    return this.ownersRef.orderByChild('userId').equalTo(id).once('value').then((snap) => {
      console.log(snap.val());
      console.log('just returned getController snap.val');
      return snap.val();
      });
  }

//more code continues here but not needed...

登录后从auth.service.ts控制台获取数据

Angular is running in the development mode. Call enableProdMode() to enable 
the production mode.
Brian Beardmore
{-LG_PkzB4VV0AjdgKgnG: {…}}-LG_PkzB4VV0AjdgKgnG: 
controller: "Pellet_Pirate_1"
email: "dbrianbeardmore@gmail.com"
name: "Brian Beardmore"photo: "https://lh6.googleusercontent.com/-YpMyDa8szOw/AAAAAAAAAAI/AAAAAAAAACY/pw-_ei54cjs/photo.jpg"
userId: "IeA2gx1Jq4N3vDVovVXHSbOhlqu2"
just returned getController snap.val

我想存储controller: ''Pellet_Pirate_1''的值并将其提供给我的应用程序。用户登录时,该值从不更改。

我将不胜感激。

谢谢, 布莱恩

1 个答案:

答案 0 :(得分:0)

最简单的方法是使用LocalStorage保存信息。在Auth服务中,您需要更新身份验证的订阅部分,以将信息保存到应用程序的本地存储中。

this.user.subscribe(
      (user) => {
        if (user) {
          this.userDetails = user;
          console.log(this.userDetails);
          this.getController(this.userDetails.uid);
          this.LOGGEDIN = true;
          // save controller into local storage.
          localStorage.setItem('controller', this.getController(this.userDetails.uid));
        } else {
          this.userDetails = null;
        }
      }
    );

那么现在要做的就是每次在应用程序中加载页面时,检查本地存储,查看是否已定义控制器字段,否则将其重定向到登录页面。

这将是您的组件页面的示例构造函数:

constructor(private router: Router) {
  if(!localStorage.getItem('controller')) {
     this.router.navigate(['/loginpath']);
  }

}

更复杂的方法是使用BehaviorSubject并监视对主题的更改。