角度4绑定图像无法读取未定义的属性 [英] angular 4 binding images cannot read property of undefined
问题描述
我有一个Angular 4.0组件,以及一个带有NgFor cicle的相对HTML,后者为从我的api(使用django rest框架开发)中检索的每个"book object"创建了一个card元素.
BROWSER.HTML
<div *ngFor="let book of books" class="col s12 m2">
<div class="card">
<div class="card-image">
<img src="{{book.img_url}}" >
</div>
<div class="card-content">
<span class="card-title">{{book.book_title}}</span>
<p>ISBN: {{book.isbn}}</p>
</div>
<div class="card-action">
<a [routerLink]="['/detail', book.isbn]">This is a link</a>
</div>
</div>
</div>
我的路由器的路由是
ROUTER.TS
const routes: Routes = [
{ path: '', redirectTo: '/home', pathMatch: 'full' },
{ path: 'signup', component: SignupComponent },
{ path: 'home', component: HomeComponent },
{ path: 'books', component: BrowserComponent },
{ path: 'detail/:isbn', component: BookDetailComponent },
];
我想访问每个书本对象的详细信息页面.在我的详细信息组件中,我有:
BookDetailComponent.ts
export class BookDetailComponent implements OnInit {
book: Book;
constructor(
private bookService: BookService,
private route: ActivatedRoute,
private location: Location
) { }
ngOnInit(): void {
this.route.params
.switchMap((params: Params) => this.bookService.getBook(+params['isbn']))
.subscribe(book => this.book = book);
console.log(this.book);
}
我的图书服务是:
BOOKSERVICE.TS
@Injectable()
export class BookService {
private headers = new Headers({ 'Content-Type': 'application/json' });
private booksUrl = 'http://localhost:8000/api/books/';
getBook(isbn: number): Promise<Book> {
const url = `${this.booksUrl}${isbn}/`;
return this.http.get(url)
.toPromise()
.then(response => {
console.log(response.json());
return response.json() as Book;
})
.catch(this.handleError);
}
当我在
中使用此html代码时BookDetailComponent.html
<div class="container">
<div class="row center"">
<div class="card white col s8 offset-s2 text-cyan">
<div class="row">
<div class="col s3"><img src="{{book.img_url}}"></div>
<div class="col s9"></div>
</div>
</div>
</div>
</div>
我在Chrome控制台中拥有
ERROR TypeError: Cannot read property 'img_url' of undefined
at Object.eval [as updateRenderer] (BookDetailComponent.html:7)
at Object.debugUpdateRenderer [as updateRenderer] (core.es5.js:12822)
at checkAndUpdateView (core.es5.js:12127)
at callViewAction (core.es5.js:12485)
at execComponentViewsAction (core.es5.js:12417)
at checkAndUpdateView (core.es5.js:12128)
at callViewAction (core.es5.js:12485)
at execEmbeddedViewsAction (core.es5.js:12443)
at checkAndUpdateView (core.es5.js:12123)
at callViewAction (core.es5.js:12485)
ERROR CONTEXT DebugContext_ {view: Object, nodeIndex: 12, nodeDef: Object, elDef: Object, elView: Object}
还有这个
Error: Uncaught (in promise): TypeError: Cannot read property 'img_url' of undefined
TypeError: Cannot read property 'img_url' of undefined
每次我访问该页面时,
3-4次不同的时间.总有11个错误,有时19个...
但是我的对象已正确收到,我有
XHR finished loading: GET "http://localhost:8000/api/books/9788808122810/".
和
Object {isbn: "9788808122810", book_title: "My Title", pub_date: "2017-06-16T17:57:31Z", img_url: "https://img.ibs.it/images/someimage.png"}
图片实际上出现了在我的页面中.我只想知道为什么所有这些错误...
我的课上课,只是为了确保您掌握所有信息
export class Book {
isbn: number;
book_title: string;
pub_date: string;
img_url: string;
}
问题是当呈现组件( BookDetailComponent )时, book 属性为null,因为服务" route:ActivatedRoute "的订阅方法是异步的(了解rxjs的可观察对象),但不会返回.如果 book 属性在其中不为空,则需要使用异步管道或使用 * ngIf 或?运算符进行验证 BookDetailComponent.html
角度异步管道参考: https://angular.io/api/common/AsyncPipe
可观察的参考文献: http://reactivex.io/documentation/observable.html
I have an Angular 4.0 component, and its relative HTML with an NgFor cicle who creates a card element for each "book object" retrieved from my api (developed with django rest framework).
BROWSER.HTML
<div *ngFor="let book of books" class="col s12 m2">
<div class="card">
<div class="card-image">
<img src="{{book.img_url}}" >
</div>
<div class="card-content">
<span class="card-title">{{book.book_title}}</span>
<p>ISBN: {{book.isbn}}</p>
</div>
<div class="card-action">
<a [routerLink]="['/detail', book.isbn]">This is a link</a>
</div>
</div>
</div>
my router's routes are
ROUTER.TS
const routes: Routes = [
{ path: '', redirectTo: '/home', pathMatch: 'full' },
{ path: 'signup', component: SignupComponent },
{ path: 'home', component: HomeComponent },
{ path: 'books', component: BrowserComponent },
{ path: 'detail/:isbn', component: BookDetailComponent },
];
I'd like to access to a detail page for each book object. In my detail component i have:
BookDetailComponent.ts
export class BookDetailComponent implements OnInit {
book: Book;
constructor(
private bookService: BookService,
private route: ActivatedRoute,
private location: Location
) { }
ngOnInit(): void {
this.route.params
.switchMap((params: Params) => this.bookService.getBook(+params['isbn']))
.subscribe(book => this.book = book);
console.log(this.book);
}
my book service is:
BOOKSERVICE.TS
@Injectable()
export class BookService {
private headers = new Headers({ 'Content-Type': 'application/json' });
private booksUrl = 'http://localhost:8000/api/books/';
getBook(isbn: number): Promise<Book> {
const url = `${this.booksUrl}${isbn}/`;
return this.http.get(url)
.toPromise()
.then(response => {
console.log(response.json());
return response.json() as Book;
})
.catch(this.handleError);
}
when i use this html code in
BookDetailComponent.html
<div class="container">
<div class="row center"">
<div class="card white col s8 offset-s2 text-cyan">
<div class="row">
<div class="col s3"><img src="{{book.img_url}}"></div>
<div class="col s9"></div>
</div>
</div>
</div>
</div>
I have in the Chrome console:
ERROR TypeError: Cannot read property 'img_url' of undefined
at Object.eval [as updateRenderer] (BookDetailComponent.html:7)
at Object.debugUpdateRenderer [as updateRenderer] (core.es5.js:12822)
at checkAndUpdateView (core.es5.js:12127)
at callViewAction (core.es5.js:12485)
at execComponentViewsAction (core.es5.js:12417)
at checkAndUpdateView (core.es5.js:12128)
at callViewAction (core.es5.js:12485)
at execEmbeddedViewsAction (core.es5.js:12443)
at checkAndUpdateView (core.es5.js:12123)
at callViewAction (core.es5.js:12485)
ERROR CONTEXT DebugContext_ {view: Object, nodeIndex: 12, nodeDef: Object, elDef: Object, elView: Object}
and this
Error: Uncaught (in promise): TypeError: Cannot read property 'img_url' of undefined
TypeError: Cannot read property 'img_url' of undefined
3-4 different times every time i access that page. for a total of 11 errors sometime, sometime 19...
But my object is correctly received, I have
XHR finished loading: GET "http://localhost:8000/api/books/9788808122810/".
and
Object {isbn: "9788808122810", book_title: "My Title", pub_date: "2017-06-16T17:57:31Z", img_url: "https://img.ibs.it/images/someimage.png"}
and the picture actually appears in my page. I just like to know why all these errors...
my book class, just to be sure you have all the informations
export class Book {
isbn: number;
book_title: string;
pub_date: string;
img_url: string;
}
The problem is that when your component (BookDetailComponent) is rendered the book property is null, because the subscribe method of "route: ActivatedRoute" service is async (Learn about Observables of rxjs) and yet does not return. You need to use async pipe or verify using *ngIf or ? operator if the book property is not null in the BookDetailComponent.html
Angular async pipe ref: https://angular.io/api/common/AsyncPipe
Observable ref: http://reactivex.io/documentation/observable.html
这篇关于角度4绑定图像无法读取未定义的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!