1

I´m fairly new to Angular2 and want to load data from a JSON-file. I read the AngularIO Article and did the tutorial, but i still need some help. I splitted the "getting Data" into an apiService which loads data and a component, whicht gets the data from the apiService.

Because it´s simpler, for this question I want to load the data directly to the component without the apiService.

This is the component:

export class StatusComponent implements OnInit {

    private status = {};
    private error: string;

   constructor(private router: Router, private variables: Variables, private apiService: ApiService, private http: Http) {
        if (!this.variables.getIsLoggedIn()) {
            this.router.navigate(['login']);
        }
    }

    ngOnInit() {
        this.getStatus();
    }

    getStatus() {
       this.http.get('../app/apiFiles/status.json')
      .map((res:Response) => res.json())
      .subscribe(
        data => { this.status = data},
        err => console.error(err),
        () => console.log('done')
      );
      console.log(JSON.stringify(this.status));
    }
}

This is JSON:

{
  "status": {
    "timercount": "0",
    "reccount": "0"
   }
}

In the component, the getStatus() is correctly load, and goes through without an error, but the variable i fill status isn´t filled. After the getStatus() the variable is still {}. Moreover, the output of console.log(JSON.stringify(this.status)); is {}.

I hope someone can help me and solve it ! Thank so much!

2 Answers 2

2

That's because console.log(JSON.stringify(this.status)); is executed after http call is done. Have in mind that all http calls are asynchronous methods. Try this:

getStatus() {
   this.http.get('../app/apiFiles/status.json')
  .map((res:Response) => res.json())
  .subscribe(
    data => { this.status = data},
    err => console.error(err),
    () => console.log(this.status);
  );
}

You'll see this will print your result because () => console.log(this.status); is executed after http call is successfuly completed.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, but no, this was not the solution :/
The Solution was to use this.status = data.status , then the data is loaded... ;) But thank you very much!
0

The correct solution is this:

getStatus() {
       this.http.get('../app/apiFiles/status.json')
      .map((res:Response) => res.json())
      .subscribe(
        data => { this.status = data.status},
        err => console.error(err),
        () => console.log('done')
      );
      console.log(JSON.stringify(this.status));
    }

So, you have to use data.status, because the JSON file begins with "status" ;)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.