我使用 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。
如何finished=true
使用 angularfire2 检查 Firebase 中的值?
更新 - @Aaron Saunders 解决方案适用于我的文件
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');
}
}