Jozzy91
Jozzy91

Reputation: 97

Ionic2 angular2 http get json from external api

I am aware that this might be a noob question since I've seen more complicated stuff, but to understand the complicated I need to understand the easy stuff first.

I am trying to get the name from a JSON string from an api (laravel):

{"name":"Abigail","state":"CA"}

The code is created with a route which returns this (in laravel):

return response()->json([
    'name' => 'Abigail',
    'state' => 'CA'
]);

In ionic I got these files:

page.ts:

export class Page {
  constructor(public http: Http) {}
    getJson() {
      this.http.get('http://external.ip/api')
          .map(res => res.json())
          .subscribe(
          data => this.data = data
      );
    }
}

page.html:

<ion-header>
  <ion-navbar>
    <ion-title>App</ion-title>
  </ion-navbar>
</ion-header>
<ion-content padding>
  <ion-content>
    <ion-list>
      <ion-item>
        <h3>{{data.name}}<h3>
      </ion-item>
    </ion-list>
  </ion-content>
</ion-content>

I know this doesn't work, but I need help to get this working. I want to be able to add more names later on. And after that I want to be able to post data to the api (for example add a name or change a date).

Upvotes: 2

Views: 1712

Answers (1)

deek
deek

Reputation: 1095

This should work assuming something runs getJson()( I added OnInit code to do that). Gave a quick example of a simple post request for ya too. You can subscribe to that post or leave it as is.

//Will need on OnInit to run getJson()
    import {Component, OnInit} from '@angular/core';


 export class Page implements OnInit {

  constructor(public http: Http) {}

data: any;

    getJson() {
      this.http.get('http://external.ip/api')
          .map(res => res.json())
          .subscribe(
          data => this.data = data;
      );
    }
//run getJson() at initial load
ngOnInit() {
 this.getJson();
}
     postJson(data:any) {
    let headers = new Headers({ 'Content-Type': 'application/json'});
    let options = new RequestOptions({ headers: headers });
    return this.http.post('http://52.11.14.57:4000/api/events', JSON.stringify(data), options)
      .map((res: Response) => res.json());
  }
        }
    }

Upvotes: 3

Related Questions