离子呼叫服务

时间:2017-05-01 20:21:36

标签: angularjs angular ionic-framework

我在IONIC中定义了一个服务(文件reddit.service.ts):

r'$\mu \pm \sigma$'

}

我正在调用此服务(文件reddits.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());
}

我收到的错误消息是:

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

为什么我收到此错误?有什么问题?

2 个答案:

答案 0 :(得分:2)

似乎您的http服务未在Service构造函数中正确注入。同时确保您已导入Http& Injectable正确注入。

@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());
   }
}

另外,请在HttpModule的{​​{1}}中添加imports,以使AppModule API正常运行。

答案 1 :(得分:2)

你有一个错字:

counstructor(http:Http)

应该是:

constructor(http:Http)

通常我们只是将提供者注入构造函数,如...

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

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

<强>更新

由于之前HttpModule曾经包含IonicModule,因此不再需要HttpModule,因此需要在NgModule中导入imports并设置为super.onCreate(null); 'navigationComponentId' => '',数组。