我一直在使用angular和firebase / firestore进行项目。
我有以下代码:
this.cadet = this.cadetCollection.valueChanges().subscribe(x => {
this.cadetName = x[0].Cadet;
this.cadetCompany = x[0].Company;
this.cadetId = x[0].CadetId;
return x as Cadets[];
}));
我能够将数据记录到控制台,以及在我的html模板中通过插值使用数据。但是,我真正需要做的是将数据存储在组件属性或变量中,以便我可以使用一些数据进行计算。
我对角度和可观察性仍然很陌生,所以请善待:)
经过一番评论后,我尝试了以下方法:
this.cadets = this.cadetCollection.valueChanges().subscribe(x => {
this.cadetName = x[0].Cadet;
this.cadetCompany = x[0].Company;
this.cadetId = x[0].CadetId;
this.cadet = x[0];
console.log(this.cadet);
return x as Cadets[];
});
console.log('Cadet is ' + this.cadet);
似乎只要对象在subscribe方法中就返回到控制台,但在此之后未定义。
答案 0 :(得分:1)
假设您在同一个组件中有</
属性,您只需将cadet
分配给x[0]
:
this.cadet
提供新信息后的更新:
似乎只要对象在subscribe方法中就返回到控制台,但在此之后未定义。
不完全 - 订阅块中的代码以异步方式运行,因此购买时间this.cadetCollection.valueChanges().subscribe(x => {
this.cadet = x[0];
}));
运行,订阅块尚未执行!
答案 1 :(得分:1)
然而,我真正需要做的是将数据存储在一个 组件属性或变量,以便我可以使用一些数据 用于计算。?
您正在使用async programming ,您无法暂停代码的执行,您的订阅将在以后解决,但您无法预测何时。你可以做的是你可以将值存储在一个类属性中并在subscribe中调用一个方法,该方法确保仅在你的cadet对象填充之前调用该方法。为了更好地理解,请调用this。
public cadet=[];
this.cadet = this.cadetCollection.valueChanges().subscribe(x => {
this.cadet=x;
this.myMethod(this.cadet);//your logic
}));
答案 2 :(得分:0)
有一位用户提前发布了此答案,但我已经不再看到它了。
我能做的是创建一个在属性中设置值的方法,然后在observable的subscribe方法中调用该方法。
this.cadets = this.cadetCollection.valueChanges().subscribe(x => {
this.cadetName = x[0].Cadet;
this.cadetCompany = x[0].Company;
this.cadetId = x[0].CadetId;
this.cadet = x[0];
this.setCurrentCadet(x[0]);
console.log(this.cadet);
return x as Cadets[];
});
感谢所有评论并帮助我的人!
答案 3 :(得分:0)
您有两种选择:
async-await: Observable和Promise是异步的,这就是订阅方法中的变量未定义的原因。使用async-await,您将能够从本地变量中的subscribe获取数据。
async myMethod(){
this.cadet = await this.cadetCollection.valueChanges().subscribe(x => {
this.cadetName = x[0].Cadet;
this.cadetCompany = x[0].Company;
this.cadetId = x[0].CadetId;
return x as Cadets[];
}));
}
答案 4 :(得分:-1)
你可以像凯文所说的那样简单地做到这一点:
public cadet = {}
this.cadetCollection.valueChanges().subscribe(x => this.cadet = x ));
对于军校学员的进一步操作,您所要做的就是在进行任何计算之前检查是否已定义军校学生。