在Angular2中执行函数之前获取可观察值
我有一个简单的系统,带有来自Firebase的用户身份验证系统。我想接收当前登录用户的数据列表。我从当前登录的用户那里通过订阅Firebase提供的可观察到的信息获取信息 但是,在调用在Angular2中执行函数之前获取可观察值,angular,firebase,observable,Angular,Firebase,Observable,我有一个简单的系统,带有来自Firebase的用户身份验证系统。我想接收当前登录用户的数据列表。我从当前登录的用户那里通过订阅Firebase提供的可观察到的信息获取信息 但是,在调用getAllEmails()函数之前,不会调用在我的构造函数中设置的private authId的值。因此,${this.authId}生成未定义的。在调用我的getAllEmails函数之前,如何确保已从可观察对象准备好authId的值 import { Injectable } from '@angular/c
getAllEmails()
函数之前,不会调用在我的构造函数中设置的private authId
的值。因此,${this.authId}
生成未定义的。在调用我的getAllEmails
函数之前,如何确保已从可观察对象准备好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}`);
}
}
从'@angular/core'导入{Injectable};
从“angularfire2”导入{AngularFire,FirebaseListObservable};
从“../Email”导入{Email};
从“../auth/auth.service”导入{AuthService};
@可注射()
导出类电子邮件服务{
私有authId:string;
建造师(
私人af:AngularFire,
私有authService:authService
) {
this.authService.getUserInformation()
.subscribe(用户=>{
this.authId=user.authId;
})
}
getAllEmails():FirebaseListObservable{
返回此.af.database.list(`/emails/${this.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:string;
构造函数(专用authService:authService){
this.authService.getUserInformation()
.subscribe(用户=>{
this.authId=user.authId;
})
}
getAuthId():编号{
返回this.authId;
}
}
从“”导入{baseService}
@可注射()
导出类EmailService扩展了baseService{
私有authId:string;
构造函数(私有af:AngularFire){}
getAllEmails():FirebaseListObservable{
返回此.af.database.list('/emails/'+super.getAuthId());
}
}
第二个解决方案是:
使用另一个服务类代替基类,以获取控制器中的AuthId并传递它。我认为第一种解决方案更好。您在哪里调用getAllEmails()?ngOnInit()是的,然后将其分配给类变量谢谢。但是,您似乎忽略了EmailService中的super()调用。那看起来怎么样?当我尝试执行super(authService)时,我得到了一个errorKamran,您知道在您的设置中进行super()调用的最佳设置是什么吗?我刚刚给出了一个建议,请查看用于调用基类方法的typescript文档