如何返回这些数据

时间:2017-05-13 05:44:46

标签: angular typescript ionic2

您好我正在使用firebase开发一个ionic2应用程序。所以我有一个名为Students-services的提供程序。我在服务中输入一个函数来遍历节点并获取值。之后它将显示在数组中。一切正常。但我无法将数据返回到我的page.ts文件。 它显示了unifined.But,如果我把它放在控制台,我可以看到我需要的值。 任何人都可以帮助我。

这是我在学生服务中的功能。

settropies(userId) {
  let total = 0;
  let result = [];
  let query = this.userProfile.child(userId+'/exams/').orderByKey();

  query.on("value",(snapshot) => {
    snapshot.forEach((childSnapshot) => {
      var key = childSnapshot.key;
      var childData = childSnapshot.val();

      total = total + childData.marks;
      result.push(total);
      this.marksarray = result;  
    }); 
    this.marksarray = result;
    console.log(this.marksarray[1]);
  });
  return this.marksarray;
}

我在 my page.ts 文件

中调用了该功能
console.log(this.studentservice.settropies(studentId));

1 个答案:

答案 0 :(得分:0)

当您返回时,该数组未定义,因为

  query.on("value",(snapshot)=> {

是一个异步事件。

解决此问题的一种方法是使用eventEmitter

在您的服务中:

   public finished$ = new EventEmitter<any>();

 snapshot.forEach((childSnapshot)=> {
        var key = childSnapshot.key;
         var childData = childSnapshot.val();
         total=total+childData.marks;
         result.push(total);
         this.marksarray=result;  
          this.finished$.emit(result);
      }); 

然后在你的page.ts

里面
    constructor(){

        this.studentservice.$finished.subscribe((result)=>{
            console.log(this.studentservice.settropies(studentId));

       });
    }