2016-11-08 50 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()。你能评论地图函数调用吗?