0
votes

I am trying to show all my posts from my wordpress website. Currently there are 2 posts, you can see it in the json file: View

export class HomePage {
url: string = ‘http://feederhorgasz.000webhostapp.com/wp-json/wp/v2/posts?_embed?filter[orderby]=date&order=asc1’;
items: any;

constructor(public navParams: NavParams,public navCtrl: NavController, private http:Http) {

console.log('Passed params', navParams.data);
}
ionViewDidEnter() {
this.http.get( this.url )
.map(res => res.json())
.subscribe(data =>
{
this.items = data;
console.log(“átadott wp api”,data);

    }); 
}

However when i am trying to read from the json, it is listing only one object. (i can see it in the log)

1

1 Answers

1
votes

That is because you're telling Angular to get a single value from the result. this.items = data; where items: any; is capable of storing one value, you have to define that you're expecting an array of data not just one object. So the simple answer is:

// By adding [] it will be concidered an array
items: any[];
this.http.get(this.url)
  .map(res => res.json())
  .subscribe(data: any[] => {
    //Line below will throw error if it not defined as an array
    this.items = data;
    console.log(“átadott wp api”, data);
  });

You're style of code can lead you to a messy project; what I meant is that you should not mix components and services together, as you have now. It is very beneficial keep services out of component as this will reduce the workload if you have to change one of the http.get method for instance; down the line. I'll add snippet for what you should ideally have.

Homepage Component

export class HomePage {

  items: Type[];
  constructor(public navParams: NavParams, public navCtrl: NavController, private posts: HomepageService) {

    console.log('Passed params', navParams.data);
  }

  ionViewDidEnter() {
    this.post.getPosts().subscribe(data: Type[] => {
        this.items = data;
        console.log(“átadott wp api”, data);
    });
  }

HomepageService

@Injectable()
export class HomepageService {
  url: string = "http://feederhorgasz.000webhostapp.com/wp-json/wp/v2/posts?_embed?filter[orderby]=date&order=asc1";

    constructor(private http: Http) {}

  getPosts(): Observable < Type[] > {
    return this.http.get(this.url)
      .map(res => res.json() as Type[])
      .catch((err: Response) => Observable.throw(console.log(err)));
  }

As you can see, if you want to change the URL of the endpoint, you only need to update single file; not all the component that you've written that service.

Class (Type)

You should also use classes to map response JSON so Angular can interact with it as an object, instead of some type of string. Class