我想计算从我的Firebase数据库作为可观察项返回的一组项目的总价。但是,该服务不会返回任何内容。
这是我尝试的内容:
服务
getRooms(): any {
let result = {};
this.items
.toPromise()
.then(items => {
for (let item of items) {
let name = item.name;
let price = item.price;
if (name in result) {
result[name] += price;
} else {
result[name] = price;
}
}
});
return result;
}
组件
export class InspirationComponent implements OnInit {
rooms: any;
constructor(private inspirationService: InspirationService) {
this.items = this.inspirationService.getRooms();
}
ngOnInit() {
}
}
答案 0 :(得分:3)
对于初学者来说,你不应该像这样填充变量this.items
。
你应该这样做:
<强>组件强>
export class InspirationComponent implements OnInit {
rooms: any;
constructor(private inspirationService: InspirationService) {
this.inspirationService.getRooms().then(result => {
this.items = result ;
});
}
<强>服务强>
getRooms(): any {
return this.http.get('url')
.map(items => {
let result = {}
for (let item of items) {
let name = item.name;
let price = item.price;
if (name in result) {
result[name] += price;
} else {
result[name] = price;
}
}
return = result ;
}).toPromise();
}
答案 1 :(得分:0)
我认为你必须解决你的承诺。更改组件。
export class InspirationComponent implements OnInit {
rooms: any;
constructor(private inspirationService: InspirationService) {
this.items = this.inspirationService.getRooms((result) => {console.log(result);});
}
ngOnInit() {
}
}