无法在this.afAuth.authState.subscribe()方法之外读取uid,它在我重新加载页面后说uid未定义

时间:2018-04-30 02:49:40

标签: angular firebase firebase-realtime-database angularfire2

*这是My Product.Service,我在重新加载页面后未定义uid,但它是在我第一次登录后定义的,我不知道为什么,请任何人帮我发​​现这个问题,我搜索了但我没有找到解决方案,我问了很多人,但没有人回答我,我是Angular的新手

        import { Injectable, EventEmitter, Output } from "@angular/core";
        import { AngularFireDatabase, FirebaseListObservable } from 'angularfire2/database-deprecated';
        import * as firebase from 'firebase/app';
        import { AngularFireAuth } from 'angularfire2/auth';

        import { Product } from "./models/product.model";
        import { METHODS } from "http";

    @Injectable()
    export class ProductService{

        products: FirebaseListObservable<Product[]>;
        user : firebase.User;
        users : Array<any> = [];
        final_data: Array<any> = [];
        uid:string;


        constructor(
            private db: AngularFireDatabase,
            private afAuth: AngularFireAuth
            ) {
                this.afAuth.authState.subscribe(auth => {
                  if (auth !== undefined && auth !== null) {
                    this.user = auth;

                    console.log(this.user.uid);// uid is defined here
                  }
                });

                console.log(this.user.uid);// uid is undefined here


            }





           getProducts(): FirebaseListObservable<Product[]>{



                return this.db.list(`users/${this.user.uid}/products`);
           }

这是我的组件,它显示了产品:

import { Component, OnInit, Input, AfterViewChecked, OnChanges } from '@angular/core';
import { Product } from '../models/product.model';
import { ProductService } from '../product.service';
import { ShoppingCartService } from './shopping-cart.service';
import { AuthServiceService } from '../auth-service.service';
import { FirebaseListObservable } from 'angularfire2/database-deprecated';
import { AngularFireAuth } from 'angularfire2/auth';

@Component({
  selector: 'app-shopping-cart',
  templateUrl: './shopping-cart.component.html',
  styleUrls: ['./shopping-cart.component.css']
})
export class ShoppingCartComponent implements OnInit, OnChanges {


  products:FirebaseListObservable<Product[]>;
  productsArray : Product[];
  sum:number = 0;

  constructor( private ProdService: ProductService, private afAuth: AngularFireAuth) {


   }

  ngOnInit() {
    this.afAuth.authState.subscribe(
      auth => console.log(auth.uid, " Shopping Cart") // uid is defined
    )


    this.products = this.ProdService.getProducts(); // uid is undefined here






  }
  ngOnChanges(){
    this.products = this.ProdService.getProducts(); // uid is undefined here





  }



}

1 个答案:

答案 0 :(得分:0)

使用Angular或SPA,您需要在用户端管理会话。服务器不会为您管理会话。您需要将令牌存储到本地存储&amp;还定义了刷新令牌(即,在一段时间后,firebase令牌到期)。查看本教程here