【问题标题】:Getting Observable value before executing function in Angular2在Angular2中执行函数之前获取可观察值
【发布时间】:2023-03-28 01:39:01
【问题描述】:

我有一个简单的系统,带有 Firebase 的用户身份验证系统。我想接收当前登录用户的数据列表。我通过订阅 Firebase 的 observable 从当前登录用户那里获取信息。

但是,在调用getAllEmails() 函数之前,不会调用在我的构造函数中设置的private authId 的值。因此${this.authId} 产生未定义。在调用 getAllEmails 函数之前,如何确保已从 observable 中准备好 authId 的值?

import { Injectable } from '@angular/core';
import { AngularFire, FirebaseListObservable } from 'angularfire2';
import { Email } from '../email';
import { AuthService } from '../auth/auth.service';

@Injectable()
export class EmailService {

  private authId: string;

  constructor(
    private af: AngularFire,
    private authService: AuthService
  ) {
    this.authService.getUserInformation()
      .subscribe(user => {
        this.authId = user.authId;
      })
  }    

  getAllEmails(): FirebaseListObservable<any> {
    return this.af.database.list(`/emails/${this.authId}`);
  }

}

【问题讨论】:

  • 你在哪里调用 getAllEmails()? ngOnInit()
  • 是的,然后将其分配给类变量

标签: angular firebase observable


【解决方案1】:

您可以为此做几件事

  1. 创建基础服务类并在基础类的构造函数中获取authId
  2. 在Component的构造函数中获取authId并调用getAllEmails(authId)

解决方法如下:

export class baseService{

private authId: string;

  constructor(private authService: AuthService) {
    this.authService.getUserInformation()
      .subscribe(user => {
        this.authId = user.authId;
      })
  }
getAuthId(): number{
       return this.authId;
}
}

import {baseService} from '<yourPath>'

@Injectable()
export class EmailService extends baseService {

  private authId: string;

  constructor(private af: AngularFire) {  }    

  getAllEmails(): FirebaseListObservable<any> {
    return this.af.database.list('/emails/'+ super.getAuthId());
  }

}

第二个解决方案是:

而不是基类有另一个服务类来获取控制器中的 AuthId 并传递它。我认为第一个解决方案要好一些。

【讨论】:

  • 谢谢。但是,您似乎忽略了 EmailService 中的 super() 调用。那看起来怎么样?当我尝试做 super(authService) 我得到一个错误
  • Kamran,您知道使用您的设置进行 super() 调用的最佳设置是什么吗?
  • 我只是给了一个建议,请查看 typescript docs 以调用基类方法
猜你喜欢
  • 2022-11-29
  • 1970-01-01
  • 2018-01-15
  • 2017-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-16
相关资源
最近更新 更多