【问题标题】:Angular Fire 2 : getting last element in FirebaseListObservable list.Angular Fire 2:获取 FirebaseListObservable 列表中的最后一个元素。
【发布时间】:2017-05-20 18:28:25
【问题描述】:

我有一个从 Firebase 获取的 FirebaseListObservable 列表。我的对象看起来像这样:

{
  "0" : {
    "completed" : false,
    "description" : "Grab the grocerry",
    "id" : 25,
    "status" : true,
    "title" : "Grocerry"
  },
  "1" : {
    "completed" : false,
    "description" : "some task",
    "id" : 26,
    "status" : true,
    "title" : "Complete this"
  }
}

这里我想按顺序更新 Id,一种使用 forEach 的 FirebaseListObservable 方式。但随着名单的增加,这将过于昂贵。所以我的问题是, 1)我怎样才能找到一些带有 ID 的元素。 2)如何获取ID的最后一个索引以便顺序更新ID。

我的代码:

import { Component, OnInit } from '@angular/core';
import { todo } from  '../shared/todo';
import {AngularFireDatabaseModule,AngularFireDatabase, FirebaseListObservable} from 'angularfire2/database';
import {AngularFireAuthModule, AngularFireAuth } from 'angularfire2/auth';

@Component({
  selector: 'app-add-task',
  templateUrl: './add-task.component.html',
  styleUrls: ['./add-task.component.css']
})
export class AddTaskComponent {
    newTask :todo = new todo();
    finalObject : todo = new todo();
    active: boolean = true;
    todos: FirebaseListObservable<any[]>;
    constructor(afAuth: AngularFireAuth, db: AngularFireDatabase) {
     // this.user = afAuth.authState;
      this.todos = db.list('todos');
    }
    onSubmit() {
        console.log(this.newTask);
        console.log(this.todos);
        this.finalObject = {
            'id' : 29,
            'title' : this.newTask.title,
            'description' :this.newTask.description,
            'status':true,
            'completed' :false
        };
        //this.todos.push(this.newTask);

        this.newTask = new todo();
        /* To reset the form*/
            this.active=false;
            setTimeout ( ()=> this.active=true,0);
        /* To reset the form*/
    }
}

【问题讨论】:

    标签: angular firebase firebase-realtime-database angular2-forms angularfire2


    【解决方案1】:

    你可以这样做:

    import 'rxjs/add/operator/do';
    
    this.todos = db.list('todos').do(data => this.length = data.length);
    

    当您想更新最后一项时,只需执行以下操作:

    db.list('todos').update(this.length - 1, newData);
    

    【讨论】:

    • .do() 方法对我不起作用,因为 FirebaseListObservable 列表不支持它。你能建议其他方法吗,
    • 如果是从rxjs导入的话。
    猜你喜欢
    • 2014-05-01
    • 2017-02-18
    • 1970-01-01
    • 2022-01-01
    • 2012-10-21
    • 2010-10-30
    • 1970-01-01
    • 2022-11-15
    • 1970-01-01
    相关资源
    最近更新 更多