javascript - Angular 2 中的 Http get 请求

标签 javascript jquery angular jsonp ionic2

我正在尝试从 Statbureau 通胀 api- https://www.statbureau.org/en/inflation-api 检索数据使用 Angular 2。我开始测试我的 api 并确保它在控制台中输出成功消息。看来我使用的 api 是 JSONP,因为我使用的 JSON 地址 http://www.statbureau.org/calculate-inflation-price-jsonp?jsoncallback= ? 在网站上,他们提供了一个 JS fiddle,可以使用 jquery 成功调用 api。当我尝试在 Angular 2 中进行相同的调用时,出现以下错误:

TypeScript error: C:/Users/Rennie/projects/inflator/app/pages/home/home.ts(22,13): Error TS
2322: Type 'Observable<any>' is not assignable to type 'HomePage'.
  Property 'jsonp' is missing in type 'Observable<any>'.
TypeScript error: C:/Users/Rennie/projects/inflator/app/pages/home/home.ts(22,13): Error TS
2409: Return type of constructor signature must be assignable to the instance type of the c

这是我的代码

import {Component} from '@angular/core';
import {NavController} from 'ionic-angular';
import {Jsonp, URLSearchParams } from '@angular/http';
import {Observable} from 'rxjs/Rx';
import 'rxjs/add/operator/map';
@Component({
  templateUrl: 'build/pages/home/home.html'
})
export class HomePage {


  constructor(private jsonp: Jsonp) {

    this.jsonp=jsonp;
        let cpiUrl = "https://www.statbureau.org/calculate-inflation-price-jsonp?jsoncallback"
         let params = new URLSearchParams();
      params.set('country', 'united-states');
      params.set('amount', '102');
        params.set('start', '1968/1/1');
        params.set('finish', '2016/1/1');
        // TODO: Add error handling
        return this.jsonp
               .get(cpiUrl, { search: params }).map(function(response){ return response.json(); })

    }


}

我的代码与 jsfiddle 中的调用不同,因为我对 api 参数进行了硬编码,只是为了快速查看结果。

最佳答案

1) 构造函数通常(总是?)没有 return 语句。删除 return 语句应该处理 type 'Observable<any>' is not assignable to type 'HomePage'.

2)好像没有办法get关于Jsonp类(class) Angular 2检查docs .

3)可观察的序列/管道在订阅之前不会被执行(它们是惰性的),所以即使该代码确实编译了,请求也不会被执行。

4) 我认为你应该看看this类似的问题。

祝你好运。

关于javascript - Angular 2 中的 Http get 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38381296/

相关文章:

javascript - jQuery show() 未按预期工作

jquery - 如何使用 jQuery AJAX 和 Spring MVC 3 从服务器下载文件

jquery - 如果浏览器高度或宽度发生变化但保持比例,则缩放图像

javascript - 返回带有过滤子数组的父对象

javascript - 将 CSS 应用到 ionic 2 选项卡和导航栏

javascript - 如何使用 Raphael Canvas 库创建多层图像?

javascript - 使用 JSONP,我有 'ReferenceError: data not defined'

javascript - AngularJS 路由, Controller 不执行

javascript - Angular Material 2 自动完成,mat-option 元素不触发 keyup 事件

javascript - 单击单选按钮时折线图不显示数据