Angular2 http get restfull api request not working

I just got into angular2 and ran into a problem i don’t see how i could fix. I was trying to get some data from a restfull api and that all worked just fine. The problem was that when i tried another restfull api, just as a test, it would not get me the data.

So a call to this api worked: http://jsonplaceholder.typicode.com/posts

works() {
    return new Promise(resolve => {
        this.http.get('http://jsonplaceholder.typicode.com/posts')
        .map(res => res.json())
        .subscribe(data => {
             this.data = data;
             console.log(data);
             resolve(this.data);
        }, error => console.error(error));
    });
  }

But a call to this api did not: http://gokhankaradas.com/wp-json/posts it always goes to the error condition. (Object {_body=Event error, status=200, statusText=”Ok”, …})

doesNotWork() {
    return new Promise(resolve => {
        this.http.get('http://gokhankaradas.com/wp-json/posts')
        .map(res => res.json())
        .subscribe(data => {
             this.data = data;
             console.log(data);
             resolve(this.data);
        }, error => console.error(error));
    });
  }

Am i missing something?

1
Leave a Reply

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Jason
Guest

I might have solved it myself.

I created a simple result via laravel, a product list, and just spit it out in a json format and then tested it. It also failed like the failing api.

public function test(Product $product){
    $products = $product->get();
    return Response::json($products, 200);
}

Then i added the following code to the routes.php and it worked. So i guess the api that was failing didnt have that. Not too sure bout it but it seems to fix my problem 😉

header('Access-Control-Allow-Origin:  *');
header('Access-Control-Allow-Methods:  POST, GET, OPTIONS, PUT, DELETE');