AngularFire 2:从构造函数以外的函数访问Firebase DataBase

时间:2017-07-06 13:52:19

标签: firebase firebase-realtime-database angularfire angularfire2

我在我的项目中有一个情况,我希望在提交函数中获取db.list(),而不是像我们通常那样在构造函数或init mehtod中。这样做背后的共鸣是。我有一个标记功能,它具有用户ID,并由用户在下拉列表中选择。现在,我的数据库设计为:

UserID1
|- Task 1
|- Task 2
UserID2
|- Task 1
|- Task 2

现在On Submit我想推送用户已选择的userID中的数据,并且它是数据库层次结构中的子分支,如何获取相同的数据。

代码:

import { Component, OnInit } from '@angular/core';
import { todo } from  '../shared/todo';
import {AngularFireDatabaseModule,AngularFireDatabase, FirebaseListObservable} from 'angularfire2/database';
import {AngularFireAuthModule, AngularFireAuth } from 'angularfire2/auth';
import * as firebase from 'firebase';
import { Observable } from 'rxjs/Observable';
import { Router} from '@angular/router';

@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();
    todoListHighestId : number=10;
    userId : string;
    user: Observable<firebase.User>;
    active: boolean = true;
    userList: FirebaseListObservable<any[]>;
    todos: FirebaseListObservable<any[]>;
    todosEdit : FirebaseListObservable<any[]>;
    constructor(afAuth: AngularFireAuth, db: AngularFireDatabase , private router : Router) {
    /*------- Authentication Handler ---------*/

     this.user = afAuth.authState;
      this.user.subscribe ((userState)=>{
        console.log("UserState",userState);
        if(!userState){
          this.router.navigateByUrl('/Login');
         }else {
            this.userId  = userState.uid;
         } 
         //this.todos = db.list('todos/'+this.userId);
         this.todosEdit = db.list("todos/",{preserveSnapshot:true});
         this.userList = db.list("users/");
         this.userList.subscribe(snapshots=> {
            snapshots.forEach(snapshot => {
                console.log(snapshot);
            })
         });
      });
     };

    /*------- Authentication Handler ---------*/
    onSubmit( db: AngularFireDatabase ) {
        console.log("New Task",this.newTask);
        //this.todos=db.list("todos/"+this.newTask.userID)
        this.todosEdit.subscribe(snapshots=> {
            snapshots.forEach(snapshot => {
                if(snapshot.val().id){
                    this.todoListHighestId = snapshot.val().id;
                    //console.log("this.todoListHighestId",this.todoListHighestId, snapshot.val().id)
                }
                else {
                    this.todoListHighestId = 10;
                }
            });
        });
        this.finalObject = {
            'id' : this.todoListHighestId+1,
            'title' : this.newTask.title,
            'description' :this.newTask.description,
            'status':true,
            'completed' :false,
            'userID':this.newTask.userID
        };
       /**** This newtask has the userID where I want to save my task ***/
        db.list("todos/"+this.newTask.userID).push(this.finalObject);

        console.log("final OBject",this.finalObject);
        this.newTask = new todo();
        /* To reset the form*/
            this.active=false;
            setTimeout ( ()=> this.active=true,0);
        /* To reset the form*/
    }
}

0 个答案:

没有答案