Calling http service


#1

I’ve a service provider:

class Data

getData(): any {
http.get(‘http://localhost:3000/get-data’)
.map(res=> { this.data1 = res.json(); });
}

Now I want to import this and use the data in one of my pages:
1. So I import the provider class i.e., Data
2. Create an instance of it.
3. Now, how do I call getData() method and get the data from my provider?


#2

You don’t want to be creating instances. Let DI do that for you.

@Component
 export class Page {
  constructor(private _data:Data) {
  }

  method(): void {
    this._data.getData().subscribe((data) => {
      // do something with data
    });
  }
}

#3

Its not working for me :frowning:

Can you please give me a simple example?

  1. a service page - with http get call.
  2. a simple page where we use the service.

#4

My issue is:

I’m getting an array from my server and I’m assigning it to *ngFor but it says it can’t itterate object!!
But I’ve checked it many times, and I’m passing array and not object :frowning: