正如我在标题中所说,如何在可观察的内部获取变量?
temp$ : Observable<any[]>;
onChange(changedValue){
this.temp$ = this.database.list('Libraries/').valueChanges();
this.temp$.subscribe((data) =>{
console.log(data);
});
}
这个函数帮助我通过数据库获取数据,将数据推送到名为 temp$ 的 Observable 中。
我可以从 Google Chrome 的控制台看到 temp$ 里面的内容,这是完全正确的,但我无法访问 nameOfCity 变量..
0: {nameOfCity: " esk", nameOfLibrary: "yaa"}
1: {nameOfCity: " esk", nameOfLibrary: "baskabir"}
2: {nameOfCity: " Tokat", nameOfLibrary: "dasdas"}
3: {nameOfCity: " Sivas", nameOfLibrary: "asdasd"}
4: {nameOfCity: " Sivas", nameOfLibrary: "bsad"}
5: {nameOfCity: " esk", nameOfLibrary: "dsad"}
6: {nameOfCity: " Tokat", nameOfLibrary: "dd"}
.
.
.
如何从 temp$ 变量中获取 nameOfCity,例如 temp.nameOfCity
提前致谢!
最佳答案
首先要明确的是,包含您要查找的数据的不是 temp$
,而是箭头函数中的变量 data
确实如此。由于您必须订阅 Observable 才能获取您正在寻找的数据,因此下面的代码片段应该以正确的方式指导您。
onChange(changedValue) {
this.database.list('Libraries/').valueChanges()
.subscribe((data) => {
// data seems to be an array of object from your example
// Having this in mind, you can iterate over the array and
// cityInfos will be used to identify the objects
for (let cityInfos of data) {
console.log(cityInfos);
console.log(cityInfos.nameOfCity);
console.log(cityInfos.nameOfLibrary);
}
});
}
对此进行扩展,您应该能够重新声明在箭头函数范围内可访问的变量,更具体地说,是 3 个 console.log
所在的位置。
关于javascript - ionic 3 : How can i get variable inside observable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53797241/