I am sure the problem is about asynchronization but I could not find the solution. I have created a service which gets an array of JSON data. In my component, I would like to show this data when the page is loaded. I don't get any data when the page is loaded, but I created a button and put the same function on its onclick event. I get the data on on click event. What am I doing wrong?
my component
import { Component } from '@angular/core';
import {PostService} from './post.service';
@Component({
selector: 'app-root',
template: `
{{test}}
<ul>
<li *ngFor="let item of jsonArray">
{{item.title}} a
</li>
</ul>
<button on-click="onClick()">button</button>
`
})
export class AppComponent {
test;
jsonArray : any[];
constructor(private _postService : PostService){
}
onClick(){
this.jsonArray = this._postService.getPosts();
this.test = "clicked";
}
ngOnInit(){
this.jsonArray = this._postService.getPosts();
this.test = "init";
}
}
and my service class
import {Http} from '@angular/http'
import 'rxjs/add/operator/map';
import {Injectable} from '@angular/core';
@Injectable()
export class PostService {
private _url = "https://jsonplaceholder.typicode.com/posts";
jsonArray: any[];
getPosts():any[]{
//return this._http.get(this._url).map(res =>res.json());
this._http.get(this._url).subscribe(response => {
this.jsonArray = response.json();
console.log(response.json());
console.log("jsonArray",this.jsonArray);
});
return this.jsonArray;
}
createPost(post){
return this._http.post(this._url,JSON.stringify(post)).map(res =>res.json());
}
constructor(private _http:Http ){
}
}