我需要帮助我的Angular代码。我只想从Firebase获取数据,但控制台日志返回带有空对象的数组。我已经从我的Firebase创建了数据! 这是我的服务:
import { Injectable } from '@angular/core';
import { AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument } from 'angularfire2/firestore';
import { Item } from '../models/Item';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class ItemService {
itemsCollection: AngularFirestoreCollection<Item>;
items: Observable<Item[]>;
constructor(public afs: AngularFirestore) {
this.items = this.afs.collection('/items').valueChanges();
}
getItems() {
return this.items;
}
}
这是我的组件
import { Component, OnInit } from '@angular/core';
import { ItemService } from '../../services/item.service';
import { Item } from '../../models/Item';
@Component({
selector: 'app-items',
templateUrl: './items.component.html',
styleUrls: ['./items.component.css']
})
export class ItemsComponent implements OnInit {
items: Item[];
constructor(private itemService: ItemService) { }
ngOnInit() {
this.itemService.getItems().subscribe(items => {
console.log(items);
this.items = items;
});
}
}
这是我的模板:
<div *ngIf="items?.length > 0;else noItem">
<ul *ngFor="let item of items | async">
<li>
{{item.title}}
</li>
</ul>
</div>
<ng-template #noItems>
<hr>
<h5>No Items</h5>
</ng-template>
我的结果在Array中没什么。你能帮助我吗,非常感谢!
Angular is running in the development mode. Call enableProdMode() to enable the production mode.
core.js:3687
Array []
答案 0 :(得分:0)
这是因为在分配订阅值之前,您正在安排items数组。试试这个
this.items = items;// First assign the value
console.log(this.items);// then Console it out