2016-02-27 323 views
1

我試圖做Angular2一個AJAX請求,按照官方的文檔一個Ajax請求:https://angular.io/docs/ts/latest/api/http/Http-class.html角2拋出意外的標記錯誤,當我嘗試做

我不斷收到錯誤Uncaught SyntaxError: Unexpected token <文件中angular2-polyfills.js:1243

我只是跟着5分鐘的教程和Hello World示例工作正常,但是當我試圖實現AJAX請求時,錯誤開始拋出。

什麼是造成這個問題,我該如何解決它?

我的代碼:

import {Component} from 'angular2/core'; 
import {Http, HTTP_PROVIDERS} from 'angular2/http'; 

@Component({ 
    selector: 'my-app', 
    viewProviders: [HTTP_PROVIDERS], 
    templateUrl: 'app/main.html' 
}) 

export class LeadsList { 
    constructor(http: Http) {} // This line is causing the error. 
} 

// Throws the error: Uncaught SyntaxError: Unexpected token < in the file angular2-polyfills.js:1243 
+0

嘗試使用'私有HTTP:在構造函數中Http'。而不是'http:http' –

+0

試過了。沒有效果。 – Weblurk

+0

似乎你的代碼沒有錯誤。你會爲你的代碼創建plnkr嗎?虐待幫助你。 –

回答

1

我必須包括http.min.js文件,以使其工作,以及在構造函數中使用進樣。

所以基本上我在index.html文件添加此:

<script src="node_modules/angular2/bundles/http.min.js"></script> 

而在我的組件文件,我改變了這個

constructor(http: Http) 

這樣:

constructor(@Inject(Http) http: Http) 

中當然我還必須從核心庫中導入Inject

import {Component, Inject} from 'angular2/core'; 
1

你應該使用供應商屬性,而不是viewProviders定義你的組件時一個:

import {Component} from 'angular2/core'; 
import {Http, HTTP_PROVIDERS} from 'angular2/http'; 

@Component({ 
    selector: 'my-app', 
    providers: [HTTP_PROVIDERS], 
    templateUrl: 'app/main.html' 
}) 

export class LeadsList { 
    constructor(http: Http) {} // This line is causing the error. 
}