我很早就开始在Angular2中找到恼人的错误,在控制台中我遇到了这个错误
onError:SyntaxError:JSON.parse:JSON数据第1行第1列的意外字符
这是我的book.service.ts代码
import { Injectable } from 'angular2/core';
import { Book } from './book';
import {Http} from 'angular2/http';
import 'rxjs/add/operator/map';
@Injectable()
export class BookService{
books:Array<Book>;
constructor(private _http: Http) {
}
getBooks() {
return this._http.get('/api/books')
.map(res => res.json());
}
}
我的app.component.ts
import {Component} from 'angular2/core';
import { BookService } from './book.service';
import { Book } from './book';
import {BooksFilterPipe} from './book.filter';
import {HTTP_PROVIDERS} from 'angular2/http';
@Component({
selector: 'my-app',
templateUrl: 'app/book.component.html',
providers: [BookService, HTTP_PROVIDERS],
pipes: [BooksFilterPipe]
})
export class AppComponent{
books:Array<Book>;
constructor(private _bookService: BookService) { }
getBooks() {
this._bookService
.getBooks()
.subscribe(
books => this.books = books,
error => console.log('onError: %s', error)
);
}
ngOnInit() {
this.getBooks();
}
}
我的ApiController(路由很好)
<?php
namespace Books\Controller;
use Bootstrap\App;
class ApiController extends App{
public function getBooksAction(){
$em = $this->getEntityManager();
$books = $em->getRepository('Books\Model\Books')->findAll();
$newBooks = [];
foreach ($books as $book) {
$newBooks[] = $book->toArray();
}
return $this->renderAjax($newBooks);
}
}
这是我的命令控制台日志
的console.log(this._bookService.getBooks());
帮我解决问题。