【问题标题】:Angular 2 HTTP GET returning URL nullAngular 2 HTTP GET 返回 URL null
【发布时间】:2016-09-23 00:12:38
【问题描述】:

我正在尝试使用带有 Typescript 的 angular 2 发出一个简单的 HTTP GET 请求。我收到一个 404 错误,URL 为空。下面显示的是我的组件文件,以及我收到的错误。

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { BreadcrumbService } from './breadcrumbService';
import { Http, Response } from '@angular/http';

@Component({
  moduleId: module.id,
  providers: [ BreadcrumbService],
  templateUrl: 'html/appList.html',
  styleUrls: ['css/list.css']

})
export class HealthComponent {
  constructor(private http: Http) {
      this.http.get('http://jsonplaceholder.typicode.com/posts/1')
      .toPromise()
      .then((res: Response) => {
      console.log('RES: ', res);
      })
    .catch((err: Error) => {
      console.log('ERR!!: ', err);
    });
   }
}

错误信息:

Response {_body: Object, status: 404, ok: false, statusText: "Not Found",     headers: Headers…}
 _body:Object
 headers:Headers 
 ok:false
 status:404
 statusText:"Not Found"
 type:2
 url:null
 __proto__:Body

【问题讨论】:

  • 你用的是什么版本的angular 2?
  • @galvan 看起来是 2.0.0 beta .17 但我正在使用 import @angular/http
  • 我有同样的问题 - 运气好吗?
  • @Yuvals 我从来没有解决它。我相信这是http导入的问题。我对这个项目不是很远,所以我只是下载了一个已经导入并正在工作的 http 的启动项目......
  • @MalindaMiller 我相信我找到了问题..请参阅下面的答案。

标签: http angular get


【解决方案1】:

这可能是InMemoryWebApiModule.forRoot 相关问题。当您加载内存中的 api 但尝试访问未定义的 url 时会发生这种情况。解决这个问题的方法是在app.module config 中设置passThruUnknownUrl: true

InMemoryWebApiModule.forRoot(InMemoryDataService, {passThruUnknownUrl: true}) ..

【讨论】:

  • 非常感谢,我遇到了同样的问题,这绝对是一个可行的解决方案。我将不得不更多地研究 InMemory 模块导致这种行为的原因。 stackoverflow.com/questions/41752254/…
【解决方案2】:

如您所见,这是一个 404 错误,请分析您对服务器的请求。 404错误意味着没有找到您请求的内容。

关于如何提出请求,请尝试使用.map 而不是toPromise

尽量不要在构造函数上发出 HTTP 请求,而是使用 ngOnInit。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-28
    • 2017-06-14
    • 2016-04-03
    • 2016-11-08
    • 2019-03-30
    • 1970-01-01
    • 2016-10-07
    • 2023-01-13
    相关资源
    最近更新 更多