1

I am able to get data from an api using http.get, within http.get console.log showing data but out of http get it showing undefined data even not setting data to class variables in html it is giving error of undefined here is how i am getting data in provider

provider method

if (this.data) {
    return Promise.resolve(this.data);
  }

    return new Promise(resolve => {
        this.http.get(SERVER_NAME+'home')
          .map(res => res.json())
          .subscribe(data => {
            this.data = data;
            resolve(this.data);
          });

      });

home.ts

  this.homeService.getHomeData().then(data => {
      this.homeData = data;
      console.log(this.homeData); // here it is showing data.
    });

home.html

<ion-slides class="home-slide" autoplay="3000" loop>
  <ion-slide *ngFor=" let banner of homeData">
       <img src="assets/images/1_2.jpg" class="img-responsive" alt="">
  </ion-slide>        
</ion-slides>

API data

here is my json data coming from api, I am creating just one request to fetch home page data, data is little complex.

{
    "banners": [
        {
            "image": "http://localhost/upload/banner-1.jpg"
        },
        {
            "image": "http://localhost/upload/banner-12.jpg"
        }
    ],
    "watch_brands": [
        {
            "name": "A",
            "slug": "a"
        },
        {
            "name": "Brand from app",
            "slug": "brand-from-app"
        },
    ],
    "watches": [
        [
            {
                "name": "Geneve White Dial Y/G",
                "slug": "geneve-white-dial-yg",
                "brand_name": "Test Brand for watch",
                "images": {
                    "200": "http://localhost/dwe/cdv_photo_00144.jpg",
                    "400": "http://localhost/dwe/cdv_photo_00144.jpg"
                }
            },
            {
                "name": "Vintage Diamond Bezel and Bracelet White Dial Y/G",
                "slug": "vintage-diamond-bezel-and-bracelet-white-dial-yg",
                "brand_name": "Test Brand",
                "images": {
                    "200": "http://localhost/dwe/cdv_photo_00530.jpg",
                    "400": "http://localhost/dwe/cdv_photo_00530.jpg"
                }
            }
        ]
    ]
}

other version of json data just for banners

[
    {
        "image": "http://localhost/upload/banner-12.jpg"
    },
    {
        "image": "http://localhost/upload/banner-1.jpg"
    }
]
umefarooq
  • 4,540
  • 1
  • 29
  • 38

1 Answers1

1

I'd change a few things in your code to make it work:

import 'rxjs/add/operator/toPromise'; // <- I've added this import

public yourMethod(...): Promise<any> {

  if (this.data) {
    return Promise.resolve(this.data);
  }

  return this.http.get(SERVER_NAME + 'home')
             .map(res => res.json())
             .map(data => {

               // Save the data
               this.data = data;

               // Return the data to the subscribers
               return this.data;

              })
              .toPromise() // <- Transform the observable into a Promise :)

}

Like you can see there, I'm using the toPromise operator to transform the observable into a promise, and I'm also using the map operator to save the data in the this.data instead of subscribing to the observable.

Then when you want to call that method, you just need to:

this.homeService.getHomeData().then(data => {
  this.homeData = data;
  console.log(this.homeData); // here it is showing data.
});
sebaferreras
  • 44,206
  • 11
  • 116
  • 134
  • 1
    No luck still result is same, undefined. why fetching data with http so much complex in ionic 1 it was really easy. is there any easy way to fetch data in angular and ionic, i have updated my question you can find my api json data also in it. – umefarooq Jun 29 '17 at 10:25
  • 1
    What happens if you add this to your view?: `

    {{ homeData | json }}

    `
    – sebaferreras Jun 29 '17 at 10:42
  • 1
    it drive me crazy man, now i fond the real problem is ion-slider autoplay is the root of the problem. i am fetching data easyly – umefarooq Jun 29 '17 at 13:29
  • So the data is being obtained properly, right? If that's the case, please mark the answer as accepted so we can close the issue :) – sebaferreras Jul 01 '17 at 07:42
  • can you tell me how to check errors, like 404, 401 errors with above method. – umefarooq Jul 01 '17 at 15:58
  • Sure, take a look at [this SO answer](https://stackoverflow.com/questions/39870972/catch-401-exception-in-angular2) – sebaferreras Jul 01 '17 at 16:26