我尝试从我的Firebase检索数据并且它可以正常工作,但是JUST用于console.log()。 我无法将值返回到var ...
我正在使用Angular 2&打字稿我有
服务:
import {Injectable} from "angular2/core";
import 'rxjs/Rx';
import {Observable} from "rxjs/Observable";
declare var Firebase: any;
@Injectable()
export class DataService {
getAllData() {
const firebaseRef = new Firebase('https://XYZ.firebaseio.com/path/user')
firebaseRef.on("value", function (snapshot) {
console.log(snapshot.val()); // THIS WORKS!
return snapshot.val(); // THIS DOES NOT WORK!
});
}
和一个组件:
@Component({
templateUrl: 'templates/user.tpl.html',
providers: [DataService],
})
export class UserComponent implements OnInit{
userData: any;
constructor(private _dataService: DataService){}
ngOnInit():any {
this.userData = this._dataService.getAllData();
console.log(this.userData); // THIS DOES NOT WORK: UNDEFINED
}
如果我运行它,我的userData var得不到任何东西......我无法解决这个问题。我以为我需要一个Observable但是我失败了,无论我试图做什么......
有人可以帮忙吗?
答案 0 :(得分:3)
由于Firebase是事件驱动的,因此您需要将调用包装成一个observable:
getAllData() {
const firebaseRef = new Firebase('https://XYZ.firebaseio.com/path/user')
return Observable.create((observer) => {
firebaseRef.on("value", function (snapshot) {
console.log(snapshot.val());
observer.next(snapshot.val());
});
});
}
通过订阅返回的observable,您将能够获得价值:
ngOnInit():any {
this._dataService.getAllData().subscribe(data => {
this.userData = data;
});
}