【问题标题】:how to fetch data from service in angular 6?如何从 Angular 6 中的服务中获取数据?
【发布时间】:2018-12-16 04:35:14
【问题描述】:

我将这个 api 用于我的演示应用程序 (https://restcountries.eu/)

API url 是这个 https://restcountries.eu/rest/v2/all

但我无法以角度从服务中获取数据

这是我的代码 https://stackblitz.com/edit/angular-3jpqrc?file=src%2Fapp%2Fapp.component.ts

constructor(private dataservice : DataService){

     this.dataservice.fetchDataThroughPromise().subscribe(()=>{
      console.log('s')
    })
  } 

服务代码

 fetchDataThroughPromise(){
    return this.http.get('https://restcountries.eu/rest/v2/all',
      {
        headers :new HttpHeaders({
          'content-type': 'application/json'
        })
      });
  }

使用 Angular cli 创建项目时查看错误

【问题讨论】:

    标签: javascript angular


    【解决方案1】:

    只需删除:

        headers :new HttpHeaders({
          'content-type': 'application/json'
        })
    

    最终代码:

    fetchDataThroughPromise() {
      return this.http.get('https://restcountries.eu/rest/v2/all')
    }
    

    【讨论】:

    • 是的,您的答案在在线编辑器中可以正常工作。但是为什么当我使用 angular cli 创建项目时它不起作用
    • 查看我的更改我在本地项目中遇到此错误
    • 我用 angular-cli 创建了一个新项目。我已经在 app.component.ts 及其作品中完成了您的请求
    • hmm ..我发现我的问题我添加了memolize libraray
    猜你喜欢
    • 2020-02-12
    • 2020-11-15
    • 2020-09-08
    • 1970-01-01
    • 2019-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-29
    相关资源
    最近更新 更多