【发布时间】:2018-07-06 02:37:55
【问题描述】:
我正在开发一个 Angular+Firebase 项目。我正在尝试将我的数据上传到 firebase 数据库。但是我在做的时候遇到了错误。下面是我的 FirebaseService 代码。
import { AngularFirestore } from 'angularfire2/firestore';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { AngularFireDatabaseModule, AngularFireDatabase } from 'angularfire2/database';
import { AngularFireObject, AngularFireList } from 'angularfire2/database';
import * as firebase from 'firebase';
@Injectable()
export class FirebaseService {
listings ;
listing: Observable<any[]>;
folder: any;
constructor(private db: AngularFireDatabase) {
this.folder = 'listingimages';
}
getListings(){
this.listings = this.db.list('/listings').snapshotChanges().map(actions => {
return actions.map(action => ({ key: action.key, ...action.payload.val() }));
})
return this.listings;
}
getListingDetails(id){
this.listing = this.db.object('/listings/'+id).valueChanges() as Observable<Listing[]>;
return this.listing;
}
addListing(listing){
//Create Root Reference
let storageRef = firebase.storage().ref();
for(let selectedFile of [(<HTMLInputElement>document.getElementById('image')).files[0]]){
let path = `/${this.folder}/${selectedFile.name}`;
let iRef = storageRef.child(path);
iRef.put(selectedFile).then((snapshot) => {
listing.image = selectedFile.name;
listing.path = path;
console.log(this.listings);
return this.listings.push(listing);
});
}
}
}
interface Listing{
$key?: string;
title?: string;
type?: string;
image?: string;
city?: string;
owner?: string;
bedrooms?: string
}
我不明白为什么它显示未定义的错误?
【问题讨论】:
-
listings是undefined... 初始化它。 -
谢谢。我试图初始化它,但现在出现了一个新错误。 Observable
不能分配给 'any[]'。 -
你能把:“this.listing = this.db.object('/listings/'+id).valueChanges() as Observable
”改成:“this.listing = this.db.object('/listings/'+id).valueChanges() as Listing[]"?
标签: angular firebase firebase-realtime-database angular2-services angularfire2