2016-11-08 40 views
2
一個簡單的HTTP GET調用

我想從我的Angular2應用做一個簡單的HTTP GET要求:不能在Angular2

this.http.get("https://mybaseurl.com/hello") 
    .map(res => res.json()) 
    .subscribe(
    function(response) { console.log("Success Response" + response)}, 
    function(error) { console.log("Error happened" + error)}, 
    function() { console.log("the subscription is completed")} 
); 

Node.js服務器配置是這樣的:

app.get('/hello', function(req, res) { 
    res.send("hellow world"); 
}); 

當我打電話,我不斷收到此錯誤:

caused by: unable to parse url 'https://mybaseurl.com/hello'; original error: Cannot read property 'split' of undefined 
    at InMemoryBackendService.parseUrl (in-memory-backend.service.ts:518) 
    at InMemoryBackendService.handleRequest (in-memory-backend.service.ts:279) 
    at InMemoryBackendService.createConnection (in-memory-backend.service.ts:240) 

任何想法什麼是我做錯了?

編輯:粘貼整個類代碼:

import {Component} from '@angular/core'; 
import {Auth} from './auth.service'; 
import {AuthHttp} from 'angular2-jwt'; 
import {Http} from '@angular/http'; 
import 'rxjs/add/operator/map'; 

@Component({ 
    selector: 'ping', 
    templateUrl: 'app/ping.template.html' 
}) 
export class ApiService { 

    API_URL: string = 'https://myapp.herokuapp.com'; 
    message: string; 

    constructor(private auth: Auth, private http: Http, private authHttp: AuthHttp) {} 

    public ping() { 

    this.http.get(`${this.API_URL}/hello`) 
     .map(res => res.json()) 
     .subscribe((response) => { 
     console.log("Success Response" + response) 
     }, 
     (error) => { console.log("Error happened" + error)}, 
     () => { console.log("the subscription is completed")} 
    ); 
    }  
} 

=====> 這看起來像在Angular2一個巨大的錯誤 - 所有http requests返回null,或者描述它的錯誤消息是不是在所需模式。 我有人有我喜歡的HTTP GET工作演示,瞭解

+1

似乎並不與上面的代碼的問題。一個建議 - 使用'()=>'而不是'function()',因爲'function()'將導致'this.'不再指向當前的類實例。也許你已經在你發佈的代碼之外,這裏會導致錯誤。 –

+0

我從localhost調用到heroku應用程序(https://myherokuapp.com)。這是相關的嗎? – Yuvals

+0

@GünterZöchbauer這沒有幫助。非常奇怪的是我試圖調用一個返回JSON的工作服務,我得到:'狀態錯誤:404 Not Found for URL:null' – Yuvals

回答

2

它看起來像使用在@NgModuleHttp.get同時導致未發現的網址返回空和錯誤。

這樣設置它爲我工作: InMemoryWebApiModule.forRoot(InMemoryDataService, {passThruUnknownUrl: true})

0

檢查使用箭頭功能成功和錯誤如下:

this.http.get("https://mybaseurl.com/hello") 
    .map(res => res.json()) 
    .subscribe((response) => { console.log("Success Response" + response)}, 
    (error) => { console.log("Error happened" + error)}, 
    () => { console.log("the subscription is completed")} 
); 
+0

得到相同的錯誤... – Yuvals

1

也許這是東陽你的答案從服務器 - 您發送字符串到客戶端,但在map函數中,您嘗試調用res.json()。你能評論地圖函數調用嗎?