2016-02-13 96 views
0

下面我在浏览器中得到一个JavaScript错误代码:角2的Http未捕获的SyntaxError:意外的标记<

Uncaught SyntaxError: Unexpected token < 

如果我从image.service.ts删除constructor(private _http:Http) { },不会再出现错误。

我错误地使用http吗?我将如何去做一个http服务,它只是返回json?

App.compontent.js

import {Component, OnInit} from 'angular2/core'; 
import {Image} from './image'; 
import {ImageDetailComponent} from './image-detail.component'; 
import {ImageService} from './image.service'; 

@Component({ 
    selector: 'my-app', 
    directives: [ImageDetailComponent], 
    providers: [ImageService], 
    template: ` 
    <h1>{{title}}</h1> 
    <h2>Choose your security image</h2> 
    <button (click)="getImageData()">Get Image Data!</button> 
    <ul class="images"> 
     <li *ngFor="#image of images" 
     (click)="onSelect(image)"> 
     <img class="image-responsive" src="{{image.imageurl}}"> 
     </li> 
    </ul> 
    <my-image-detail [image]="selectedImage"></my-image-detail> 
    ` 
}) 

export class AppComponent implements OnInit{ 
    title = 'Authenticate'; 
    images: Image[]; 
    selectedImage: Image; 

    constructor(private _imageService: ImageService) { } 

    getImages() { 
    this._imageService.getImages().then(images => this.images = images); 
    } 
    ngOnInit() { 
    this.getImages(); 
    } 

    onSelect(image: Image) { this.selectedImage = image; } 
} 

image.service.js

import {Image} from './image'; 
import {Injectable} from 'angular2/core'; 
import {Http} from 'angular2/http'; 

@Injectable() 
export class ImageService { 

    constructor(private _http:Http) { } 
    items: Array<Image>; 

    getImageData() { 
    this._http.get('http://localhost/pincode/api/src/1.0/get/images.php') 
     .map(res => res.json()) 
     .subscribe(
     data => this.items = data, 
     err => this.logError(err), 
     () => console.log('Got Images') 
    ); 
    return this.items; 
    } 

    logError(err) { 
    console.error('There was an error: ' + err); 
    } 

    getImages() { 
    return Promise.resolve(this.getImageData()); 
    } 

} 
+1

能否请您搜索。有几十个这样的问题。 –

+2

最常见的原因是:你的api发送一些HTML错误页面。 – Sirko

+0

查看浏览器网络面板中的内容。有可能你的服务器返回一些html而不是有效的js源码。 (html5应用程序的常见问题) –

回答

1

我认为你忘了包括Angular2的HTTP JS文件:

<script src="node_modules/angular2/bundles/angular2-polyfills.js"></script> 
<script src="node_modules/systemjs/dist/system.src.js"></script> 
<script src="node_modules/rxjs/bundles/Rx.js"></script> 
<script src="node_modules/angular2/bundles/angular2.dev.js"></script> 
<script src="node_modules/angular2/bundles/http.dev.js"></script> <----- 
+0

这种错误通常是由于语法错误。如果不包含'http',Angular会轻易失败,我想。 – jeerbl

+0

我在过去看到,这样的消息是一个模块的404响应的结果...这表示很难从发生此错误的问题来理解;-) –

+0

我错过了bundle/http.dev.js文件。 此外,我没有导入HTTP_PROVIDERS – ClickThisNick

相关问题