2016-02-27 320 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. 
}