使用下面的代码,我在浏览器中收到了javascript错误:
Uncaught SyntaxError: Unexpected token <
如果我从constructor(private _http:Http) { }
删除image.service.ts
,则不会再出现错误。
我错误地使用http
了吗?我如何制作一个只返回json的http
服务?
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());
}
}
答案 0 :(得分: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> <-----