angularjs - ionic 调用服务

标签 angularjs angular ionic-framework

我在 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/

相关文章:

javascript - 如何在 index.html angular 8 中使用 *ngIf

javascript - 根据Id替换Array中的数据

node.js - 从 Angular 4 升级到 5 : "NodeInvocationException: No provider for PlatformRef!"

angularjs - 无法使用 AngularJS 在我的 http 帖子中发送字符串

javascript - 使用 true/false 应用 ng-class

ios - 即使使用 Cordova WKWebview Engine 插件的基本 Ionic 项目也会产生白屏

ionic-framework - 如何等待 PouchDB 成功连接

javascript - 将我的列表 vom ng-repeat 更改为 collection-repeat 后 ng-click 无法正常工作

javascript - Angular POST 请求

jquery - JSON:是否可以有一个具有多个值的键?