2016-09-23 105 views
4

我正在试着用Typescript创建一个简单的HTTP GET请求。我得到一个404错误,与空网址。下面显示的是我的组件文件,以及我收到的错误。Angular 2 HTTP GET返回URL null

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 
+0

你用什么版本的角2? – galvan

+0

@galvan看起来是2.0.0测试版.17,但我使用导入@角/ http –

+0

我有同样的问题 - 运气? – Yuvals

回答

1

正如你可以看到,这是一个404错误,分析你的请求到服务器。 404错误意味着你找不到的东西。

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

尝试不在构造函数上发出HTTP请求,而是使用ngOnInit。

4

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

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

+0

非常感谢,我遇到了同样的问题,这绝对是一个可行的解决方案。我将不得不更多了解为什么InMemory模块导致此行为。 http://stackoverflow.com/questions/41752254/angular2-http-geturl-is-returning-404-on-a-valid-url-that-c​​an-be-retrieved-usi/41752435?noredirect=1#comment70698057_41752435 – SuperTetelman