我使用firebase作为数据库,并通过angularfire2访问它。
这是整个TodoComponent.ts文件,所以您可以得到完整的图片,但我需要的主要内容是在finishedTodo()中。

import { Component, OnInit} from '@angular/core';
import { AngularFire, FirebaseObjectObservable ,FirebaseListObservable } from 'angularfire2';

@Component({
    template: `
<h2>ToDo</h2>

<input
        #newTodo
        [(ngModel)]="todoinput"
        placeholder="add ToDo"
        (keyup.enter)="addTodo(newTodo.value)"
        type="text"
/>
{{ todoinput }}
<br>
{{ item | async | json }} ///here I am getting the value as a json string, but I don't know how to make it do what i need

<div *ngFor="let todo of todos | async">
    {{todo.todo}}
    <button (click)="deleteTodo(todo.$key)">Delete</button>
    <button (click)="finishedTodo(todo.$key)">Finished</button>
</div>

    `
})

export class ToDoComponent implements OnInit{
    item: FirebaseObjectObservable<any>;
    todos: FirebaseListObservable<any>;

    constructor(private _af: AngularFire) {
    }

    ngOnInit(){
        this.todos = this._af.database.list('hr/todos');
        this.item = this._af.database.object('/hr/todos/1');
    }

    addTodo(newTodo: string){
        this.todos.push({
            todo: newTodo
        } )
    }

    deleteTodo(key: string){
        if(confirm("U sure u want to delete " + key + " ?")){
            this.todos.remove(key)
        }
    }

    finishedTodo(key: string, finished: boolean){
        this.todos.update(key,{finished: true})
    }
}

在finishedtodo()中,我可以设置finished = true,但在此之前,我想检查firebase字段是否finished = true or false,并使切换正常工作,以便根据此条件添加特殊的css。
firebase看起来是这样的:
typescript - 如何使用angularfire2在Firebase中检查值?-LMLPHP
如何使用AngularFire2检查FireBase中的finished=true值?
更新- @亚伦桑德斯解决方案适合我的文件
isFinished;

finishedTodo(key: string, finished: boolean){

    var snapshotFinished = this._af.database.object('hr/todos/'+ key,{ preserveSnapshot: true})

    snapshotFinished.subscribe(snapshot => {
        this.isFinished = snapshot.val().finished;
    });

        if (this.isFinished == false || this.isFinished == null){
            this.todos.update(key,{finished: true});
            console.log('is false');
        }
        else{
            this.todos.update(key,{finished: false});
            console.log('is true');
        }
}

最佳答案

   var i = this._af.database.object('/hr/todos/1', { preserveSnapshot: true })
   i.subscribe(snapshot => {
    console.log(snapshot.key)
    console.log(snapshot.val().finished)
  });

来自,来自

关于typescript - 如何使用angularfire2在Firebase中检查值?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38285988/

10-12 00:33
查看更多