Angular2: http service fail to get json data

1,631 views
Skip to first unread message

jian...@gmail.com

unread,
Apr 22, 2016, 7:01:35 AM4/22/16
to AngularJS
#1. API
Return json: 
{"error":0,"data":[{"job_id":"s2323143455","status":"Enable","creator":"user1","last-modified":"2016-04-20"},{"job_id":"sdfsdf132434","status":"Enable","creator":"user2","last-modified":"2016-04-20"}]}

#2. job.service.ts
import {Injectable} from 'angular2/core';
import {Http} from 'angular2/http';
import {Observable} from 'rxjs/Observable';

@Injectable()
export class JobsService {
  constructor(public http: Http) {}

  private _jobsUrl = ' http://127.0.0.1/api/jobs/status'; 

  getJobStatus () {
    return this.http.get(this._jobsUrl)
                    .map(res => res.json());
  }

}
#3. job.component.ts
import {Component} from 'angular2/core';
import {JobsService} from './jobs.service'

@Component({
  selector: 'jobs',
  ...
    providers: [JobsService]
})
export class JobsComponent{
  jobs = "";

  constructor(
    private _jobService: JobsService
  ) {}

  getjobsStatus() {
    this._jobService.getJobStatus().subscribe(
      data => this.jobs = data,
      err => console.log(err)
    )
  }

  ngOnInit() {
   
    this.getjobsStatus();
    console.log('jobs data is ', this.jobs);
  }
}



when I print "this.jobs" in ngOnInit, always return an empty object, why ? anyone can help to fix,

thanks a lot.

Zlatko Đurić

unread,
Apr 22, 2016, 10:29:00 AM4/22/16
to AngularJS
Oh, that's because your jobs have not been fetched yet. When ou call getJobStatus() on jobService, it merely  fires the request. It does not complete the request.

So your code is executed like this (from ngOnInit forward):

- this.getjobsStatus()   // on jobsComponent
- getjobsStatus calls jobsService.getJobStatus()
- that, in turn, _prepares_ the http request and stuff. Doesn't send anything yet (or it even might). It does not, however receive an instant reply, and instead it returns.
- now your console.log("jobs data is ", this.jobs) is called, printing nothing.

Now you wonder what's going on, but later...
- then that actual http request gets fired. (by the browser, outside of JS VM)
- then the server does its mojo and returns a json
- then your function is returned.


If you want to actually see the results once they're back, you should edit your JobsComponent.getjobsStatus like this:

  this._jobService.getJobStatus().subscribe(
    response => {
      this.jobs = response.data;
      console.log('jobs data is ', this.jobs);
    },
    errorResponse => console.log(err)
  );

Classic async issue.

jian...@gmail.com

unread,
Apr 22, 2016, 10:32:52 PM4/22/16
to AngularJS
@Zlatko Đurić 

thanks for your help.

that's right, after log "this.jobs" in subscribe function, it's working fine.

but another problem is:
when I use ngFor to loop this.jobs, it also get an error "EXCEPTION: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays. in [jobs in JobsComponent@11:12]"


I know we use promise to solve this problem in angular1,X, but what about angular2?

thanks!

Zlatko Đurić

unread,
Apr 23, 2016, 1:54:19 AM4/23/16
to ang...@googlegroups.com
Well, it looks like it is because you assign it a string initially, in the class declaration. That later makes the `this.data = data` stringify the array (and if you do a `[].toString()` you get ` '[object Object]'`).

So declare it initially as array: `jobs = [];` - or be explicit about it, so that compiler helps you: `jobs: <any[]> = []`;. That way angular will expect it to be an array right away. You can even specify the type (if you have a Job class): `jobs <Job[]> = [];`. That way you're dead sure angular will get it right.




--
You received this message because you are subscribed to a topic in the Google Groups "AngularJS" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/angular/1jnfzhfmNGk/unsubscribe.
To unsubscribe from this group and all its topics, send an email to angular+u...@googlegroups.com.
To post to this group, send email to ang...@googlegroups.com.
Visit this group at https://groups.google.com/group/angular.
For more options, visit https://groups.google.com/d/optout.



--
Zlatko

jian...@gmail.com

unread,
Apr 23, 2016, 9:41:54 AM4/23/16
to AngularJS
@Zlatko Đurić .

it works now, thanks very much. 
Reply all
Reply to author
Forward
0 new messages