检查身份验证状态

检查身份验证状态

本文介绍了AngularFire/Firebase-检查身份验证状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注意:这是我的新手,请原谅一些显而易见的事情.非常感谢任何帮助:)

Note: I'm new to all of this, please excuse what might be obvious. Any help is massively appreciated :)

我有什么

  • 用于登录和注销的身份验证服务
  • 相册服务,用于根据用户ID提取项目
    • 相册列表>用户ID> albumKey
    • An auth service to log in and out
    • An album service to fetch items based on user id
      • albumList > UserId > albumKey

      问题

      • 如果要复制"localhost:4200/albums"的URL并将其粘贴到另一个选项卡中,控制台将读取

      • 结果,什么也没有加载,并且粘贴的URL也无法维护
      • 问题

        • 我是否需要在所有组件中添加可观察的用户?
        • 如何确保在加载数据之前检查用户状态?
        • 是否可以仅将我的Auth.Service用作所有其他组件的参考点?

        我的身份验证服务

        import { Injectable } from '@angular/core';
        
        import { AngularFireAuth } from 'angularfire2/auth';
        import * as firebase from 'firebase/app';
        import { Router } from '@angular/router';
        import { Observable } from 'rxjs/Observable';
        
        @Injectable()
        export class AuthService {
          user: Observable<firebase.User>;
        
        
          constructor(
            private firebaseAuth: AngularFireAuth,
            private router: Router) {
            this.user = firebaseAuth.authState;
          }
        
          login(email: string, password: string) {
            this.firebaseAuth
              .auth
              .signInWithEmailAndPassword(email, password)
              .then(value => {
                console.log('Nice, it worked!');
                console.log(this.firebaseAuth.auth.currentUser.uid);
        
                this.router.navigate(['/albums'])
              })
              .catch(err => {
                console.log('Something went wrong:', err.message);
              });
          }
        
          logout() {
            this.firebaseAuth
              .auth
              .signOut();
          }
        
        
        }

        我的相册列表服务

        注释:如果我删除了结尾为用户ID的albumList查询(注释查询),则可以将URL复制并粘贴到新标签中,并维护URL(URL. com/相册).但是,任何数据都不会首先由用户键过滤.

        note: If i remove the albumList query with the user id on the end (commented out query), I can copy and paste the URL into a new tab and the URL is maintained (url.com/albums). However, any data won't be filtered by the user key first.

        import { Injectable } from '@angular/core';
        import { AngularFireDatabase, FirebaseListObservable, FirebaseObjectObservable } from 'angularfire2/database';
        
        import { AngularFireAuth } from 'angularfire2/auth';
        import * as firebase from 'firebase/app';
        import { Observable } from 'rxjs/Observable';
        
        @Injectable()
        export class ProjectsListService {
          albumList: FirebaseListObservable<any[]>;
          user: Observable<firebase.User>;
        
          constructor(
            private database: AngularFireDatabase,
            private firebaseAuth: AngularFireAuth) {
        
            //this.albumList = database.list('/albumList');
            this.albumList = database.list('/albumList/' + this.firebaseAuth.auth.currentUser.uid);
            //console.log(this.firebaseAuth.auth.currentUser.uid);
          }
        
          getAlbumList() {
            return this.albumList;
            }
        
        
        }

        推荐答案

        • 我是否需要在所有组件中添加可观察的用户?

        是的,您一直都在使用异步数据,您需要订阅来自Firebase的更改

        Yes, you are working with async data all the time, you need to subscribe to the changes coming from the firebase

        您似乎还不熟悉角度学习,对您而言,一次学习所有内容可能会更困难.您应该查看路由器教程,更确切地说是第5单元"Route Guards" .

        It seems that you are also relatively new to angular, it might be harder for you to learn everything at once. You should check the Router tutorial, more exactly the module 5 Route Guards.

        是的,这完全取决于您,这是很常见的事情.

        Yes, that's entirely up to you and it's a very common thing.

        对于类型错误,您正在尝试访问初始化应用程序时不存在的值,因为您异步获取该值,因此需要订阅authState

        As for the Type error, you are trying to accessing a value that doesn't exist when you initialize your app, since you get that asynchronously you need to subscribe to the authState

        import { Injectable } from '@angular/core';
        import { AngularFireDatabase, FirebaseListObservable, FirebaseObjectObservable } from 'angularfire2/database';
        
        import { AngularFireAuth } from 'angularfire2/auth';
        import * as firebase from 'firebase/app';
        import { Observable } from 'rxjs/Observable';
        
        @Injectable()
        export class ProjectsListService {
          albumList: FirebaseListObservable<any[]>;
          user: Observable<firebase.User>;
        
          constructor(
            private database: AngularFireDatabase,
            private firebaseAuth: AngularFireAuth
          ) {
              firebaseAuth.authState.subscribe(user => {
                console.log(user);
                if (user) {
                  this.albumList = database.list('/albumList/' + user.uid);
                }
              })
          }
        
          getAlbumList() {
            return this.albumList;
          }
        }
        

        编辑

        先前的代码不起作用,因为当您第一次运行您的应用程序时,albumList是一个空的var,这就是为什么在浏览所有内容后都能正常工作的原因,因为在此之后它已经初始化并且可以订阅它.

        Edit

        The previous code didn't work, because when you first run your app, the albumList is an empty var, that's why after you navigate everything works fine, because after that it's already initialised and you can subscribe to it.

        因此,由于您依赖于auth状态,因此您应该在组件上订阅albumList.为什么?因为如果您的用户出于某种原因注销,那么您还将隐藏信息.

        So because you depend on the auth state you should be subscribing to your albumList on your components instead. Why? Because if your user for some reason logs out, you also hide the information.

        因此,您无需在组件上使用ProjectsListService,而是将执行以下操作:

        So instead of using ProjectsListService on your component you will do something like this:

        import { Component } from '@angular/core';
        import { AngularFireAuth } from 'angularfire2/auth';
        import { AngularFireDatabase, FirebaseListObservable } from 'angularfire2/database'
        
        @Component({
          selector: 'your-component',
          template: `<ul><li *ngFor="let album of albumList | async">{{ todo.text }}</li></ul>`
        })
        export class YOURComponent {
          albumList: FirebaseListObservable<any[]>;
        
          constructor(
            private fAuth: AngularFireAuth,
            private database: AngularFireDatabase
          ) {
            fAuth.authState.subscribe(user => {
              if (user) {
                this.albumList = database.list('/albumList/' + user.uid);
                return;
              }
              this.albumList = null;
            })
          }
        }
        

        这篇关于AngularFire/Firebase-检查身份验证状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 00:39