2016-02-13 115 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

相關問題