我在 IONIC 中定义了一个服务,如下所示(文件 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());
}
}
我像这样调用此服务(文件 reddits.ts):
getPosts(category, limit){
this.redditService.getPosts(category, limit).subscribe(response => {console.log(response);
});
我收到的错误消息是:
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)
为什么我会收到此错误?怎么了?
最佳答案
您有一个拼写错误:
counstructor(http:Http)
应该是:
constructor(http:Http)
通常我们只是将提供者注入(inject)到构造函数中,例如......
@Injectable()
export class RedditService{
baseUrl: String;
constructor(private http:Http){
this.baseUrl = 'https://www.reddit.com/r';
}
}
更新:
由于 HttpModule
以前包含在 IonicModule
中,现在不再包含了,因此需要将 HttpModule
导入到NgModule
并在 imports
数组中设置。
关于angularjs - ionic 调用服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43725944/