我有以下一段代码,它们使用Firebase
和Angular
从Ionic
DB中检索记录。
它工作正常,但没有提供每个记录的键。它给了我'undefined
'
我研究了各种在线教程,看起来从valueChanges()
切换到snapshotChanges()
可以完成这项工作,但是每个在线教程都显示了一种不同的提取记录方式,我之间也存在版本差异正在使用和在线的人。
由于我来自Java世界,所以我对JS世界还很陌生。
请指导。
home.ts
export class HomePage implements OnInit {
private items$: Item[] = [];
constructor(private shoppingListService: ShoppingListService) {
this.shoppingListService.getShoppingList().valueChanges().subscribe((datas) => {
datas.forEach(data => {
console.log(data);
//data.key is undefined here
console.log("=>" + data.key + " " + data.name + " " + data.quantity + " " + data.price);
this.items$.push({key: data.key, name: data.name, quantity: data.quantity, price: data.price});
})
}, (err) => {
console.log("problem:", err);
});
}
}
ShoppingListService.ts
@Injectable()
export class ShoppingListService {
//here 'shopping-list' is the name of the table
private shoppingListRef = this.db.list<Item>('shopping-list');
constructor(private db: AngularFireDatabase) {
this.getShoppingList();
}
getShoppingList() {
return this.shoppingListRef;
}
}
Item.model.ts
export interface Item {
key?: string;
name: string;
quantity: number;
price: number
}
package.json
"angularfire2": "^5.1.0",
"firebase": "^5.5.9",
"ionic-angular": "3.9.2",
"ionicons": "3.0.0",
"rxjs": "^6.0.0",
"rxjs-compat": "^6.3.3",
离子信息
Ionic:
ionic (Ionic CLI) : 4.4.0 (C:\Users\abc\AppData\Roaming\npm\node_modules\ionic)
Ionic Framework : ionic-angular 3.9.2
@ionic/app-scripts : 3.2.0
System:
NodeJS : v10.13.0 (C:\nodejs\node.exe)
npm : 6.4.1
OS : Windows 10
答案 0 :(得分:0)
this.shoppingListService.getShoppingList().snapshotChanges().pipe(map((actions) => {
actions.map(action => {
console.log(action.payload.doc.data());
var data = action.payload.doc.data();
var id = action.payload.doc.id;
//data.key is undefined here
console.log("=>" + id + " " + data.name + " " + data.quantity + " " + data.price);
this.items$.push({key: id, name: data.name, quantity: data.quantity, price: data.price});
})
}), catchError((err) => {
console.log("problem:", err);
});
尝试一下,让我知道您是否有任何问题。请从rxjs导入管道,地图和catchError,如下所示
import { Observable, of, throwError } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
角度版本为6