Search code examples
javascriptnode.jstypescriptmean-stackangular2-services

Type Scripit # Always getting Array of zero size


I am trying to use the following code to get the value of all spams in Home.ts from my Auth.service method getSpams() which is running fine and giving results correctly in console. But when I am trying to save the result of service in Object(totalspam) of Home.ts its giving Array of zero size.

Following are the my components:

Home.ts

    import { NavController , IonicPage} from 'ionic-angular';
    import { Component } from '@angular/core';
    import { AuthService } from '../../providers/auth-service/auth-service';
    import { Spam } from '../../providers/auth-service/auth-service';
    import {Observable} from 'rxjs/Observable';
    @IonicPage()
    @Component({
      selector: 'page-home',
      templateUrl: 'home.html'
    })
    export class HomePage {

      totalspam:Spam[] = [];

      constructor(public navCtrl: NavController,private auth:AuthService) {

         this.auth.getSpams().subscribe(spam=>{this.totalspam = spam});
         console.log(this.totalspam);

      }

    }

AuthService.ts

    getSpams(): Observable<Spam[]> {
              let url = 'http://115.113.49.148:8080/allspam';
              let headers = new Headers();
              headers.append('Content-Type', 'application/x-www-form-urlencoded');
              let options   = new RequestOptions({ headers: headers });

              // get spams from api
              return this.http.get(url, options)
                  .map((response) => response.json());
          }

AuthService.ts

    export class Spam
    {
      _id:string;
      count:Number;
      spamNumber:string;
      spamType:Array<String>;  
    }

Solution

  • Your problem is you're console logging results directly after an asynchronous method. This line: console.log(this.totalspam); is being called before the value has actually changed. When you're dealing with an asynchronous request, factors such as latency, size of request and the browser itself can mean variable resolve times.

    The purpose of an asynchronous method is to run and deal with a result at a later time without blocking any other code, so console.log is invoked immediately. If you change your code to the following, provided you are getting a result back you should see the array populated:

    this.auth.getSpams().subscribe(spam => {
        this.totalspam = spam;
    
        console.log(this.totalspam);
    });
    

    If you still do not see anything, then you should check whether or not your request is returning the desired results.