【问题标题】:Calling servcie constructor in component class在组件类中调用服务构造函数
【发布时间】:2019-01-20 02:29:05
【问题描述】:

我有以下代码在服务中

  constructor(
        private afAuth: AngularFireAuth,
        private firestore: AngularFirestore,

    ){
        this.user = afAuth.authState;
        this.LoggedInUserList = firestore.collection(this.dbPath);
        this.user.subscribe(res =>{
            this.loggedInUserKey = res.uid;
            this.userDetails$ = this.LoggedInUserList.doc(res.uid);
        })
    } 

我正在访问每个组件中的值,如下所示

 constructor(
    private authService: AuthService
   ) {

  }
  ngOnInit()
  {

    this.authService.userDetails$.valueChanges().subscribe(data => {
       console.log(data);
    });

  }

在页面没有刷新之前它很好,但是当我刷新页面时,userdetails$ 变得未定义。

我是角度新手,请帮忙

注意:我之前使用的是 localstorage,但我不想使用它。 由于我将 userdetails 存储在 firestore 中,并且获取用户详细信息的相应密钥在 afAuth.authState 中,所以我拥有所有详细信息,无需用户本地存储。

更新: 后面的事情发生在组件中,authService:AuthService 正在调用服务构造函数,但在完成构造函数之前 执行下面的代码,并且该时间点对 userdetails$ 的分配尚未完成

 this.authService.userDetails$.valueChanges().subscribe(data => {
       console.log(data);
    });

谢谢

【问题讨论】:

    标签: angular service google-cloud-firestore angular6


    【解决方案1】:

    是的,这会发生,因为它是一个 js 变量,刷新时它会设置为未定义。

    使用 SessionStorage 或 localStorage 或 cookie 来存储您的数据。

    当您点击刷新时,将您的数据复制到上述任何存储中,并在初始化时将其复制回您的变量中。 检查下面的例子。将 sessionStorage 替换为 localStorage 以在 localStorage 中存储数据。

    在 AppComponent 中

        ngOnInit() {
        if (sessionStorage.getItem("user")) {
          this.data.changeUser(sessionStorage.getItem("user"));
        }
          }
    @HostListener('window:beforeunload', ['$event'])
          unloadNotification($event: any) {
            sessionStorage.setItem("user", this.getUser());
          }
    

    如果您还有任何疑问,请告诉我..

    选项 2

    将下面的代码放在 on 函数中,并在您的服务构造函数以及 oninit 函数的组件中调用它。应该工作

    this.user = afAuth.authState;
            this.LoggedInUserList = firestore.collection(this.dbPath);
            this.user.subscribe(res =>{
                this.loggedInUserKey = res.uid;
                this.userDetails$ = this.LoggedInUserList.doc(res.uid);
            })
    

    【讨论】:

    • 不,我已从会话或本地存储转移到 firstore,我将所有详细信息存储在 firestore,
    • 检查我在答案中添加了选项 2。
    猜你喜欢
    • 1970-01-01
    • 2018-06-22
    • 1970-01-01
    • 2011-12-07
    • 2019-03-14
    • 2018-03-31
    • 2019-05-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多