Angularfire2 - 检索添加的对象

Angularfire2 - retrieve added object

我试图找到一个使用 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));
}

最后,我有一些关于原子性和规则的问题。

  1. 我是否需要使用 Firebase 的事务来使其原子化?
  2. AngularFire2 从 Firebase 检索规则?如果没有,我可以 set/update 脱机获取信息并且当我上线时 Angular 可以触发写入异常吗?我应该如何在我的代码中处理这个问题?

我离有效答案很近了。那是我在 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 的事务来使其原子化吗?

答:不用,可以用multi-location update using AngularFire2. Good answer here