Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angularjs 呼叫服务_Angularjs_Angular_Ionic Framework - Fatal编程技术网

Angularjs 呼叫服务

Angularjs 呼叫服务,angularjs,angular,ionic-framework,Angularjs,Angular,Ionic Framework,我在IONIC中定义了如下服务(文件reddit.service.ts): } 我这样调用此服务(文件reddits.ts): 我收到的错误消息是: Error: Uncaught (in promise): TypeError: Cannot read property 'get' of undefined TypeError: Cannot read property 'get' of undefined at RedditService.getPosts (reddit.service.t

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

}

我这样调用此服务(文件reddits.ts):

我收到的错误消息是:

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)

为什么我会犯这个错误?有什么问题吗?

似乎您的
http
服务没有正确地注入到服务构造函数中。还要确保已正确导入
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());
   }
}
此外,请在
AppModule
imports
中添加
HttpModule
,以使
http
API工作。

您有一个输入错误:

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
数组中。

我已经用完整的RedditService脚本更新了上面的问题。你能复习一下吗?你有鹰眼+1@PankajParkar哈哈,谢谢。我更愿意说,有时候我比其他时候更瞎。所以我想我很幸运:DI从未使用过Ionic,但我最近了解到,早些时候httpModule是if-IonicModule的一部分,但现在不再是了,所以您实际上也需要将httpModule导入您的ngModule。因此,将其添加到ngModule中的imports数组中…
import{HttpModule}来自“@angular/http”@Adam请注意,此plunker是Ionic的RC7版本,因此在这里它实际上可以工作,而不必导入http模块,但您可能使用的是比RC7更新的模块,因此需要导入HttpModule。因此,您的设置应该如下所示:@PankajParkar看起来是这样的,+1表示该值;)
constructor(http:Http)
@Injectable()
export class RedditService{
  baseUrl: String;

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