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