【问题标题】:get request fail angular2获取请求失败angular2
【发布时间】:2017-03-10 10:43:12
【问题描述】:

我创建的网络服务应该使用 1 个参数发送 get 请求, 我应该从 API 中得到结果,

NetworkServices.ts

import { Injectable } from '@angular/core';
import {Http} from "@angular/http";

@Injectable()
export class NetworkServices{
  constructor(public http:Http){

  }
  getCurrency(obj){
    console.log("function fired!")
    let url = 'http://api.fixer.io/latest?base='+obj.selectedCurrency;
    console.log(obj);
    this.http.get(url)
      .toPromise()
      .then( (res) => {
          return res;
        }
      )
  }
}

结果应该是 res,这是 3 周前的工作,我不知道 angular 是如何改变的,呵呵..

错误代码是:

[19:46:04]  transpile update started ...
[19:46:06]  typescript: D:/ionic/firstApp/src/services/network.ts, line: 25 
            Property 'toPromise' does not exist on type 'Observable<Response>'.

      L24:    return this.http.get(url).toPromise();
[19:46:06]  transpile update failed       L25:
}

[19:46:06]  watch ready

希望你们能解决这个问题:)

【问题讨论】:

  • 预期的行为是什么?实际行为是什么?
  • 你有什么资源吗???检查 API url 是否命中正确的 api..
  • 也添加一个 .catch() ,如果有则显示错误。
  • 嘿伙计们,我只是更新了我添加错误的问题。 @GünterZöchbauer; @Gnujeremie; @micronyks;
  • 你必须导入toPromise

标签: angular ionic2 get-request


【解决方案1】:

你需要添加

import 'rxjs/add/operator/toPromise'

【讨论】:

    【解决方案2】:

    您的方法不返回任何内容,并且 then 回调除了将 Promise&lt;Response&gt; 转换为另一个 Promise&lt;Response&gt; 之外什么也不做。所以你的整个方法基本上是一个noop。

    代码应该看起来像

    getCurrency(obj){
        console.log("function fired!")
        let url = `http://api.fixer.io/latest?base=${obj.selectedCurrency}`;
        console.log(obj);
        return this.http.get(url).toPromise();
    }
    

    或者,如果你想返回一个包含响应的 json 主体而不是响应本身的承诺

    getCurrency(obj){
        console.log("function fired!")
        let url = `http://api.fixer.io/latest?base=${obj.selectedCurrency}`;
        console.log(obj);
        return this.http.get(url).toPromise().then(res => res.json());
    }
    

    关于你的编译错误,你需要导入 toPromise 操作符:

    import 'rxjs/add/operator/toPromise';
    

    【讨论】:

    • 嘿,如果您的代码和它们都给我相同的错误代码,我都尝试了,我在问题中更新了它。 @JB 尼泽特
    • 我修改了答案。
    猜你喜欢
    • 2016-09-07
    • 1970-01-01
    • 2016-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-18
    • 2018-05-21
    • 2018-02-20
    相关资源
    最近更新 更多