【问题标题】:Angular6 - Store a user variable in a service and access it from other components without it being undefined?Angular6 - 将用户变量存储在服务中并从其他组件访问它而不定义它?
【发布时间】:2019-03-19 03:10:32
【问题描述】:

所以我正在制作一个 Angular 应用程序,并且有一次我想存储一个用户变量(我从对 Firestore Cloud 的异步调用中获得),该变量确实已设置(使用 console.log() 检查)但是当我切换页面并尝试在 Firestore 上加载该用户的食谱时,它说我的用户变量未定义。

有没有更好的方法来做到这一点?

谢谢

编辑:代码

tryConnect(email: string, password: string) {
// u = array of users
this.usersWithId.subscribe(u => {
  for (const a of u) {
    console.log(a);
    if (a.email === email && a.password === password) {
      this.connectedUser = a;
      console.log(this.connectedUser);
      break;
    }
  }
});

}

addRecipe(recipe: Recipe) {
console.log(this.connectedUser);
this.db.collection('/recipes').add({
  name: recipe.name,
  description: recipe.description,
  meal: recipe.meal,
  steps: recipe.steps,
  servings: recipe.servings,
  cuisine: recipe.cuisine,
  userID: this.connectedUser.userID,
  ingredients: recipe.ingredients
});

【问题讨论】:

  • 你能发布一些你的代码吗?
  • @Brandon 我现在不在家,但我会的!

标签: angular typescript google-cloud-firestore angular6 webstorm


【解决方案1】:

您想做的事情应该通过rxjs/store 或类似的方式来实现。 Rxjs/store 是一个状态管理系统,您可以在其中存储应用程序中的任何内容,并且在您使用它的任何地方都会保持最新状态。

如果您想在会话中保存它,也可以选择使用sessionStoragelocalStorage

【讨论】:

  • 对了!我以前使用过 localstorage,但由于某种原因,在这种情况下没有想到它,谢谢!
【解决方案2】:

如果您还没有使用它,我建议您使用 @angular/fire

您可以通过以下方式利用 @angular/fire 来实现您的目标。

AngularFireAuth 当作为依赖注入时有一个authState 类型为Observable<firebase.User>。这本质上是您当前登录用户的状态。

现在,在您的服务中,您可以创建一个私有的BehaviorSubject<Observable<firebase.User>>next 将在您的authState 更改后立即被调用。

然后您可以公开此BehaviourSubject<firebase.User> asObservable。这个 Observable 是公开的,任何将你的服务作为依赖注入的人都可以访问 user$ 并订阅它以获取当前登录用户的状态。

这是它在代码中的样子:

import { AngularFireAuth } from '@angular/fire/auth';
import { Injectable } from '@angular/core';
import { Observable, BehaviorSubject } from 'rxjs';
import { switchMap } from 'rxjs/operators';

import { User } from '@app/shared/models/user.model';

@Injectable()
export class AuthService {

  private user: BehaviorSubject<Observable<firebase.User>> = new BehaviorSubject<Observable<firebase.User>>(null);
  user$ = this.user.asObservable().pipe(switchMap(user => user));

  constructor(
    private afAuth: AngularFireAuth
  ) {
    this.user.next(this.afAuth.authState);
  }

  loginViaCredentails(user: User) {
    return this.afAuth.auth.signInWithEmailAndPassword(user.email, user.password);
  }

  ...

}

【讨论】:

  • 我正在使用 @angular/fire 并且我读过关于身份验证用户的这种方式,但据我了解,它更像是一种将用户登录到数据库而不是我的应用程序的方式(它将检查在 Firestore 控制台中创建的帐户)。对吗?
猜你喜欢
  • 1970-01-01
  • 2018-02-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-10
  • 2022-10-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多