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.

On Friday, April 22, 2016 at 1:01:35 PM UTC+2, [email protected] wrote:
>
> #1. API
> URL:  http://127.0.0.1/api/jobs/status
> 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.
>

-- 
You received this message because you are subscribed to the Google Groups 
"AngularJS" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
Visit this group at https://groups.google.com/group/angular.
For more options, visit https://groups.google.com/d/optout.

Reply via email to