-1

This is the data.ts class where I have defined the variables of the object I want to access:

export class Data {
  id : number;
  name : string;
}

Then my mock-data.ts class where I am returning a hardcoded array of objects:

import { Data } from './data';
import { Http,Headers,RequestOptions } from  '@angular/http';

export const DATAS : Data[] = [
  { id: 11, name: 'Mr. Nice' },
  { id: 12, name: 'Narco' },
  { id: 13, name: 'Bombasto' },
  { id: 14, name: 'Celeritas' },
  { id: 15, name: 'Magneta' },
  { id: 16, name: 'RubberMan' },
  { id: 17, name: 'Dynama' },
  { id: 18, name: 'Dr IQ' },
  { id: 19, name: 'Magma' },
  { id: 20, name: 'Tornado' }
];

console.log(DATAS);

My my-service.ts class where I am returning a Promise object of type Data[].(Till here I am getting back my object fine)

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
import { Headers,RequestOptions } from  '@angular/http';
import { Observable } from 'rxjs';
import { DATAS } from '../../app/mock-data';
import { Data } from '../../app/data';

/*
  Generated class for the MyServiceProvider provider.

  See https://angular.io/docs/ts/latest/guide/dependency-injection.html
  for more info on providers and Angular DI.
*/
@Injectable()
export class MyServiceProvider {

  DATAS : Data[];

  openWebMwthod() : Promise<Data[]>{

    console.log("Here data is",DATAS);
    return Promise.resolve(DATAS);

  }

}

But, in the last step where I am calling the service from my app.component.ts file, I am getting object undefined:

import { Component, OnDestroy  } from '@angular/core';
import { Platform } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
//import { Subscription } from 'rxjs/Subscription';
import { HomePage } from '../pages/home/home';
import { MyServiceProvider } from '../providers/my-service/my-service';
import { Http,Headers,RequestOptions } from  '@angular/http';
import { Data } from './data';
import { OnInit } from '@angular/core';


@Component({
  templateUrl: 'app.html'
})
export class MyApp implements OnInit{
  rootPage:any = HomePage;
  datas : Data[];


  constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen, private myServiceProvider : MyServiceProvider) {
    platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      statusBar.styleDefault();
      splashScreen.hide();

    });
  }

 getData() : any{
   //console.log("Calling web service");
   this.myServiceProvider.openWebMwthod().then(datas => this.datas = datas);
   console.log("obj is",this.datas);
 }

   ngOnInit(): void {
     this.getData();
     console.log("Debo data:",this.getData());

  }

}

Can someone tell where I might be possibly going wrong?

Debo
  • 505
  • 4
  • 13
  • 24
  • 1
    Please always include your code as code blocks in question instead of pictures. Some people might want to debug your code and also most likely refer to your code in their answer, no one is going to write all that code long hand ;) – AT82 Aug 14 '17 at 08:18
  • 1
    Possible duplicate of [How do I return the response from an Observable/http/async call in angular2?](https://stackoverflow.com/questions/43055706/how-do-i-return-the-response-from-an-observable-http-async-call-in-angular2) – AT82 Aug 14 '17 at 08:21

2 Answers2

1

You are defining DATAS class param in your service class which gets initialised with undefined value. You are imptorting the right DATAS object from your mock object, but I think it might get overriden.

BTW, your console.log line 34 in the component might be logging way before the Promise is resolved, as promise resolution is async. Therefore you should do your logging in the then method to see what value gets resolved in the promise.

BTW v2, another console.log line 39 is not logging anything as getData is not returning anything.

eddyP23
  • 6,420
  • 7
  • 49
  • 87
1

Here's the working solution:

app.component.ts(excerpt)

 ngOnInit(){
     this.myServiceProvider.openWebMwthod()
         .subscribe((response)=>{
            this.datas = response;
            console.log("here Inside app component",this.datas);
            alert("here Inside app component"+this.datas);
        });   

  }

my-service.ts(excerpt)

openWebMwthod() : Observable<any>{


    let headers = new Headers(
        {
          'Content-Type': 'application/json',    
        }
      );

    let options = new RequestOptions({headers:headers});

    return this.http.get('https://jsonplaceholder.typicode.com/posts',options)
             .map( (res) => res.json())


  }
Debo
  • 505
  • 4
  • 13
  • 24