【问题标题】:Http, get response from server with rxjs and angular2Http,使用 rxjs 和 angular2 从服务器获取响应
【发布时间】:2016-07-16 13:32:37
【问题描述】:

我不知道我做错了什么,我没有得到服务器的任何响应来使用 Http 工作。如果有人可以更深入地了解,我将该项目添加为 plunker。

https://plnkr.co/edit/3HybQY3vcsCImbuFCWrP?p=preview

post.service.ts

  getPosts(){
   return this._http.get("http://jsonplaceholder.typicode.com/posts")
                    .map(res => res.json());
  }

app.component.ts

constructor(private _postService: PostService) {
    _postService.getPosts()
               .subscribe(res => console.log(res));
  }

【问题讨论】:

  • fiddle 出现错误,找不到 system.config.js
  • 控制台有错误吗?
  • 您发布的示例存在很多问题。几个缺失的组件和文件路径不匹配。我建议首先删除 http 并先修复它们。然后更新 plunkr
  • 操作忘记删除这些,但这并没有真正的帮助

标签: http angular rxjs


【解决方案1】:

您正在发出跨域请求

您需要在http请求头中添加一些人员:

Access-Control-Allow-Origin: *

更多详情:How to create cross-domain request (Angular 2)?

【讨论】:

【解决方案2】:

没有任何问题,重新启动我的精简服务器时工作。

【讨论】:

  • 在下面看到我的回答,plunker 也可以帮助你。
【解决方案3】:

您的代码中有两个主要错误是您的代码没有按预期运行。

  1. 您正在使用 Http 请求响应,但您尚未在配置文件中配置 @angular/http 设置,因此您必须将其添加到文件中。

    '@angular/http': {
      main: 'bundles/http.umd.js',
      defaultExtension: 'js'
    },
    
  2. 您正在尝试通过 http 获取请求,而 angular2 不允许,因此您必须更改您的网址,例如

    http://jsonplaceholder.typicode.com/posts
    

    到

    https://jsonplaceholder.typicode.com/posts
    

这是你的工作代码演示

Working Example

【讨论】:

  • 我明白了,关于配置文件等以及与 plunker 一起使用的知识还没有太多,但无论如何谢谢。
猜你喜欢
  • 1970-01-01
  • 2017-09-04
  • 2021-10-17
  • 1970-01-01
  • 2017-02-10
  • 2019-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多