【问题标题】:AngularFire Duplicate PreventionAngularFire 重复预防
【发布时间】:2017-03-18 23:13:38
【问题描述】:

我正在开展一个项目,我正在将课程推送到 firebase,我希望能够使其尽可能高效。假设我的数据如下所示

  -Classes
    -classKey1
      -startTime: ---
      -endTime: ---
      -Instructor: ---
    -classKey2
      -startTime: ---
      -endTime: ---
      -Instructor: ---

现在,当我将另一个类推入数据库时​​,我希望能够检查以确保像它一样的类不存在。如果确实存在,我想抓住它的钥匙在其他地方使用。我一直在尝试我能想到的一切,但没有任何效果。如果有人有任何想法,请告诉我。提前致谢!

【问题讨论】:

  • 你有没有尝试过?您当前推送这些值的代码是什么?
  • 另外,如果一个键已经存在并且你设置了它的值,你将覆盖那里的内容。不会有重复的。
  • 我尝试过的一些事情是订阅 firebaselistobservable,然后尝试比较结果,看看是否有任何匹配我要尝试推送的内容。然后,如果我确实找到了匹配项,则使用该匹配值键。我已经尝试过滤 observable,但它不起作用。为了推送数据,我只是使用 angularfire 提供的功能,所以每次推送时都会生成一个随机密钥。这就是我遇到麻烦的原因,因为如果我再按一次,键会有所不同,但孩子们都会一样。

标签: angular firebase angularfire2


【解决方案1】:

您订阅这些项目并搜索自己的想法是关键..

试试这样:

export class EntityModel {
   $key: string;
   $exists: () => {};

   startTime: Date = new Date();
   endTime: Date = new Date();
   Instructor: string = '';
}

@Injectable()
export class YourService {

   public entities: EntityModel[];

   private _authState: FirebaseAuthState;

   constructor(private _af: AngularFire) {
      _af.auth.subscribe(authState => {
         this._authState = authState;

         if (authState) {
            _af.database.list('/classes').subscribe(classes => {
               this.entities = classes;
            });
         }
      });
   }

   public add(entity: EntityModel) {
      if (!entity) return console.log('invalid entity!');

      if (this._authState) {
         entity.Instructor = this._authState.uid;
      }

      // trying to find an existing one ..
      const existing = this.entities &&
         this.entities.length &&
         this.entities.find(e =>
            e.startTime == entity.startTime &&
            e.endTime == entity.endTime &&
            e.Instructor == entity.Instructor
         );
      if (existing) {
         // we found one ..
         console.log('FOUND:', existing.$key);
         return;
      }

      delete entity.$exists;

      // update or create?
      if (entity.$key) {
         // update ..
         const key = entity.$key; // temporary save our key!
         delete entity.$key; // we dont want to push this into our firebase-database ..
         this._af.database.list('/classes').update(key, entity); // update entry
      }
      else {
         // create ..
         this._af.database.list('/classes').push(entity);
      }
   }
}

【讨论】:

    猜你喜欢
    • 2018-05-18
    • 1970-01-01
    • 2018-05-09
    • 1970-01-01
    • 2012-01-30
    • 2013-04-13
    • 2018-04-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多