0

Hi i'm developing an ionic2 app with firebase.So here I have a provider called Students-services.I worte a function in the service for go through a node and get values.after that it will showing in an array.all are working.But i can't return data to my page.ts file. it shows undifined.But if i put it in the console i can see the values what i need. Can anyone please help me.

here is my function in students services.

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;
}

i Called the function in my page.ts file

console.log(this.studentservice.settropies(studentId));
Jeroen Heier
  • 3,520
  • 15
  • 31
  • 32
pdm LVW
  • 149
  • 1
  • 11
  • Welcome to SO. Read [**asking help**](http://stackoverflow.com/help/how-to-ask) before posting a question. – Aravind May 13 '17 at 06:16
  • Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Saravana May 13 '17 at 06:55

1 Answers1

0

When you're returning, that array is undefined because

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

is an asynchronous event.

One way to fix this is using eventEmitter

Inside your service :

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

And then inside your page.ts

    constructor(){

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

       });
    }
Milad
  • 27,506
  • 11
  • 76
  • 85