Adam
Adam

Reputation: 2455

ionic calling a service

I defined a service in IONIC like this (file reddit.service.ts):

import {Injectable} from '@angular/core';
import {Http} from '@angular/http';
import 'rxjs/Rx';

@Injectable()
export class RedditService{
http:any;
baseUrl: String;

counstructor(http:Http){
    this.http = http;
    this.baseUrl = 'https://www.reddit.com/r';
}

getPosts(category, limit){
    return this.http.get(this.baseUrl+'/'+category+'/top.json?limit='+limit).map(res => res.json());
}

}

I am calling this service like this (file reddits.ts):

  getPosts(category, limit){
this.redditService.getPosts(category, limit).subscribe(response => {console.log(response);
});

The error Message I am getting is:

Error: Uncaught (in promise): TypeError: Cannot read property 'get' of undefined
TypeError: Cannot read property 'get' of undefined
at RedditService.getPosts (reddit.service.ts:16)

Why I am getting this error? What is wrong?

Upvotes: 2

Views: 274

Answers (2)

AVJT82
AVJT82

Reputation: 73337

You have a typo:

counstructor(http:Http)

should be:

constructor(http:Http)

and usually we just inject providers into constructor like...

@Injectable()
export class RedditService{
  baseUrl: String;

  constructor(private http:Http){
    this.baseUrl = 'https://www.reddit.com/r';
  }    
}

UPDATE:

As the HttpModule used to be included in the IonicModule before, it no longer is, and therefore the HttpModule needs to be imported in the NgModule and set in the imports array.

Upvotes: 2

Pankaj Parkar
Pankaj Parkar

Reputation: 136134

It seems like you have http service haven't injected properly inside Service constructor. Also make sure you have imported Http & Injectable injector correctly.

@Injectable()
export class RedditService {
   //make sure you have below dependency inject with private access specifier.
   //since we mentioned it private, http will be available in component context 
   constructor(private http: Http) { }

   getPosts(category, limit){
      return this.http.get(this.baseUrl+'/'+category+'/top.json?limit='+limit).map(res => res.json());
   }
}

Additionally please add HttpModule in imports of your AppModule to make http API working.

Upvotes: 2

Related Questions