0

I want to use Wordpress as a backend(just for CMS), I'm trying to pull in the post data into my angular 7 app but the post information is not showing. I can see the data in the console but I'm unable to pull in the data in my component. Any suggestions?

app.component.ts

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
  title = 'altair-global';

  constructor(private http: HttpClient) {}

  ngOnInit(): void {
    // Make the HTTP request:
    this.http.get('http://altair-global.local/wp-json/wp/v2/posts?filter[posts_per_page]=50').subscribe(data => {
      console.log(data);
    });
  }
}

insight.component.ts

<div class="container">
  <h4 class="text-center">Insight Page</h4>
  <ul>
    <li *ngFor="let post of posts | async">
      <h4>{{ post.title.rendered }}</h4>
      {{ post.date_gmt | date }}
    </li>
  </ul>
</div>
1
  • could you update your example where you actually assign the http call to your component variable ? in this example, posts are undefined Commented Dec 12, 2018 at 21:43

2 Answers 2

3

Try making the api call as a service first. Create api.service.ts

export  class  APIService {
    constructor(private  httpClient:  HttpClient) {}
    getPosts(){
      return  this.httpClient.get('http://altair-global.local/wp-json/wp/v2/posts?filter[posts_per_page]=50');
    }
}

Import it into your insight.component.ts file like so:

import { APIService } from  '../api.service'; (file path may vary)

Your insights.component should look similar to this:

import { Component, OnInit } from  '@angular/core';
import { APIService } from  '../api.service';

@Component({
    selector:  'app-insights',
    templateUrl:  './insight.component.html',
    styleUrls: ['./insight.component.css']
})

export  class  InsightComponent  implements  OnInit {

    private  posts:  Array<object> = [];
    constructor(private  apiService:  APIService) { }
    ngOnInit() {
        this.getPosts();
    }
    public  getPosts(){
        this.apiService.getPosts().subscribe((data:  Array<object>) => {
            this.posts  =  data;
            console.log(data);
        });
    }
}

Hope this helps!

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

Comments

2

this will help you:

first you need to decalre:

posts: any;

Then into your http code:

this.posts = data;
console.log(this.posts);

for more info : Fetch Wordpress API data into Angular

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.