I encountered a JavaScript error in my browser while working with the following code:
Uncaught SyntaxError: Unexpected token <
The error disappears when I remove
constructor(private _http:Http) { }
from image.service.ts
.
Could it be that I am incorrectly using http
? How can I create an http
service that simply returns JSON data?
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());
}
}