我在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);
});
为什么我收到此错误?有什么问题?
答案 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' => '',
数组。