如何将可观察值的值存储在变量或 属性 中

How to store values from an observable in a a variable or property

我一直在使用 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 模板中通过插值使用数据。然而,我真正需要做的是将数据存储在组件 属性 或变量中,以便我可以使用一些数据进行计算。

我对 angular 和 observables 还是很陌生,所以请多关照 :)

经过一些评论后,我尝试了以下操作:

    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);

似乎对象在订阅方法中时返回到控制台,但之后未定义。

假设您在同一个组件中有一个 cadet 属性,您可以将 x[0] 分配给 this.cadet:

this.cadetCollection.valueChanges().subscribe(x => {
  this.cadet = x[0];
}));

提供新信息后更新:

It seems that the object is returned to the console whenever it is within the subscribe method but is undefined after that.

不完全是 - 订阅块中的代码异步运行所以购买时间 console.log('Cadet is ' + this.cadet); 运行,订阅块尚未执行!

However what I really need to do is to store the data within a component property or a variable so that I can use some of the data for calculations.?

您正在使用 async programming you cannot pause the execution of the code and your subscription will be resolved in future but you cannot predict when. what you can do is You can store the value in a class property and invoke a method inside subscribe which ensures the method is only invoked when your cadet object is populated not before that.Refer this 以便更好地理解。

public cadet=[];
this.cadet = this.cadetCollection.valueChanges().subscribe(x => {
 this.cadet=x;
this.myMethod(this.cadet);//your logic
}));

您可以按照凯文的建议简单地执行此操作:

public cadet = {} this.cadetCollection.valueChanges().subscribe(x => this.cadet = x ));

对于cadet的进一步操作,你只需要在计算之前检查cadet是否被定义即可。

之前有一个用户发布了这个答案,但我再也看不到了。

我能够做的是创建一个在 属性 中设置值的方法,然后在可观察对象的订阅方法中调用该方法。

  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[];
});

感谢所有评论和帮助我的人!

您有两个选择:

  1. 解析器:https://angular.io/api/router/Resolve 解析器将在请求完成后更改状态。
  2. 异步等待: Observable 和 Promise 是异步的,这就是为什么 subscribe 方法中的变量未定义的原因。使用 async-await,您将能够从局部变量中的订阅中获取数据。
        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[];
        }));
        }