代码之家  ›  专栏  ›  技术社区  ›  emeraldsanto

Angular6-将用户变量存储在服务中,并从其他组件访问它而不必定义它?

  •  2
  • emeraldsanto  · 技术社区  · 7 年前

    有没有更好的办法?

    谢谢

    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
    });
    
    2 回复  |  直到 7 年前
        1
  •  0
  •   Sergey    7 年前

    你想做的事情应该通过 rxjs/store

    也可以选择使用 sessionStorage localStorage 如果要跨会话保存它。

        2
  •  0
  •   SiddAjmera    7 年前

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

    下面是如何利用

    AngularFireAuth 当作为依赖项注入时 authState 哪种类型的 Observable<firebase.User> . 这实际上是您当前登录用户的状态。

    BehaviorSubject<Observable<firebase.User>> 在这上面, next 授权状态

    然后你就可以揭露这个 BehaviourSubject<firebase.User> asObservable . 这个可观察对象是公共的,任何将您的服务作为依赖注入的人都可以访问 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);
      }
    
      ...
    
    }
    
    推荐文章