在组件类中调用servcie构造函数

时间:2018-08-13 11:09:04

标签: angular service google-cloud-firestore angular6

我在使用以下代码

  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,但是我不想使用它。 由于我将用户详细信息存储在firestore中,并且用于获取用户详细信息的对应密钥位于afAuth.authState中,因此我可以拥有所有详细信息,而无需使用用户本地存储。

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

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

谢谢

1 个答案:

答案 0 :(得分:-1)

是的,这将发生,因为它是一个js变量,并且在刷新时它将设置为undefined。

使用SessionStorage或localStorage或cookie存储数据。

单击刷新后,将数据复制到上述任何存储中,并在init上将其复制回变量中。 检查以下示例。将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);
        })