Angularfire2 - 检索添加的对象

时间:2017-11-23 01:51:55

标签: angular firebase angularfire2

我正在尝试找到一个使用angularfire2的完整示例,但我找不到一个。一些示例使用anugalrfire2与原生firebase或旧版本的angularfire。

我对如何使用angularfire2 / database创建两个具有依赖关系的文档有一些疑问。

实施例

数据库:

locations { 
 country: string
 lat: number
 long: number
 .....
}

stores {
 name: string
 locationID: string
 description: string
  .....
}

所以试图找到一种在原子创建中创建一个location和一个store的方法,如果可能的话,没有运气。然后,我可以更新newStore.locationID = newLocation.id

import { AngularFireDatabase } from 'angularfire2/database';
....
constructor(private db: AngularFireDatabase) { }

createStore(ownerID: number, storeData: Store, locationData: Location) {        

    let promises = {
        newStore: this.db.object('/stores').add(storeData),
        newLocation: this.db.object('/locations').add(locationData),
    }

    Observable.forkJoin(promises).subscribe((r) => {
        newStore.userID = ownerID;
        newStore.workingRegionID = newLocation.key;
    });
}

我还试图创建一个空的Store(使用AngularFire2),但我找不到这样做的方法。 (收到所有类型的错误)

import { AngularFireDatabase } from 'angularfire2/database';
....
constructor(private db: AngularFireDatabase) { }

createStore(ownerID: number, storeData: Store, locationData: Location) {

    let newStoreKey = this.db.object('/stores').push().key;
    let newLocationKey = this.db.object('/locations').push().key;

    storeData.userID = ownerID;
    storeData.workingRegionID = newLocationKey;

    let sets = {};
    sets['/stores/' + newStoreKey] = Store;
    sets['/locations/' + newLocationKey] = Location;

    return Observable.fromPromise(this.db.set(sets));
}

最后,我对atomicy和规则有一些疑问。

  1. 我是否需要使用Firebase的交易才能使其成为原子?
  2. 来自Firebase的AngularFire2恢复规则?如果没有,我可以离线设置/更新信息吗?当我上线时,Angular会触发写入异常吗?我怎样才能在我的代码中处理这个问题?

1 个答案:

答案 0 :(得分:0)

我接近有效答案。这就是我在storeService

中得到的
import { AngularFireDatabase } from 'angularfire2/database';
....
constructor(private db: AngularFireDatabase) { }

createStore(ownerID: string, storeData: Store, locationData: Location) {
    let newStore = this.db.list('/stores').push(undefined);
    let newStoreKey = newStore.key;
    let newLocation = this.db.list('/stores').push(undefined);
    let newLocationKey = newLocation.key;
    storeData.ownerID = ownerID;
    storeData.workingRegionID = newLocationKey;
    storeData.name = storeData.name.toLowerCase();

    let tasks = {};
    tasks["/stores/" + newStoreKey] = storeData;
    tasks["/locations/" + newLocationKey] = locationData;

    return this.db.object('/').update(tasks);
}

回答我自己的问题。

问:我是否需要使用Firebase的交易才能使其成为原子?

答:不,您可以使用AngularFire2 multi-location update。好的答案here