【问题标题】:Firebase doesn't return value (Angular 2)Firebase 不返回值(Angular 2)
【发布时间】:2016-05-04 14:38:15
【问题描述】:

我尝试从我的 Firebase 中检索数据,它可以正常工作,但仅适用于 console.log()。 我无法将值返回到 var...

当我使用 Angular 2 和 Typescript 时,我有

服务:

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 但我失败了,无论我试图做什么......

有人可以帮忙吗?

【问题讨论】:

    标签: javascript angularjs typescript firebase angular


    【解决方案1】:

    由于 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;
      }); 
    }
    

    【讨论】:

    • 谢谢!它现在可以工作了,但不知何故,这些值不会显示在我的表单构建器的输入字段(作为默认值)中:codeshare.io/XSAzO
    • 我添加了一个新问题:stackoverflow.com/questions/37031910/…
    • 实际上数据是异步加载的。所以创建表单时它不存在。我稍后会更新输入(在订阅回调中),如下所示:this.userForm.controls.username.updateValue(this.userData.username);
    猜你喜欢
    • 1970-01-01
    • 2017-08-25
    • 2017-06-12
    • 2017-03-26
    • 2017-05-14
    • 2020-12-24
    • 2017-12-01
    • 2017-07-13
    • 2017-05-17
    相关资源
    最近更新 更多