WordPress Angular 2 Theme Data Sorting/Query Issue

I am actually in the process of creating a WordPress Theme using Angular 2 and I feel stuck in some way.

One of the components I have created is one for navigation. This is the html for it. I am using an ngFor to list the pages and using a routerLink to route to the pages when clicked on. Everything works fine on that end. It is being listed properly and the routing works. This is the HTML I am using for it.

<ul class="nav navbar-nav">
 <li *ngFor="let post of posts" routerLinkActive="active"> 
  <a [routerLink]="post.slug" (click)="selectPage(post.slug)">
  {{ post.title.rendered }}
  <span>{{ post.menu_order }}</span>

So, this is where I am having issues. I am using those codes to query data from the WP REST API, and though stuff like {{post.menu_order}} works in the HTML, in the below sort function, it throws back an error at me, saying that ERROR TypeError: Cannot read property 'sort' of undefined

getPages(): Observable<Page[]> {
    return this.http
      .get(this.menuUrl2 + 'pages')
      .map((res: Response) => res.json())
      .do(res => console.log('All: ' + JSON.stringify(res)))
} // from the Page Service I am using

// from the listing component
posts: Page[];

constructor( private pagesService: PagesService, private router: Router, http: Http) {

   .subscribe(res =>
     this.posts = res);

this.posts.sort((a: any, b: any) => {
  if (a.menu_order < b.menu_order)
    return -1
  else if (a.menu_order > b.menu_order)
    return 1
    return 0

I have checked where the error may be coming from and it seems that the data from the API is data I can only access from doing interpolation.

So, my question is, is there something I did wrong ? How can I fix this ?

Read more here: WordPress Angular 2 Theme Data Sorting/Query Issue

Leave a Reply

Your email address will not be published. Required fields are marked *