角度 4 绑定图像无法读取未定义的属性
[英] angular 4 binding images cannot read property of undefined
本文介绍了角度 4 绑定图像无法读取未定义的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 Angular 4.0 组件,它的相关 HTML 带有一个 NgFor cicle,它为从我的 api(使用 django rest 框架开发)检索的每个书对象"创建一个卡片元素.
BROWSER.HTML
<div class="card"><div class="card-image"><img src="{{book.img_url}}" >
<div class="card-content"><span class="card-title">{{book.book_title}}</span><p>ISBN:{{book.isbn}}</p>
<div class="card-action"><a [routerLink]="['/detail', book.isbn]">这是一个链接</a>
我的路由器的路由是
ROUTER.TS
const 路由:Routes = [{ path: '', redirectTo: '/home', pathMatch: 'full' },{ path: 'signup', 组件: SignupComponent },{ path: 'home', 组件: HomeComponent },{ path: 'books', 组件: BrowserComponent },{ path: 'detail/:isbn', 组件: BookDetailComponent },];
我想访问每个图书对象的详细信息页面.在我的细节组件中,我有:
BookDetailComponent.ts
导出类 BookDetailComponent 实现 OnInit {书:书;构造函数(私人书籍服务:BookService,私人路线:ActivatedRoute,私人位置:位置) { }ngOnInit(): 无效 {this.route.params.switchMap((params: Params) => this.bookService.getBook(+params['isbn'])).subscribe(book => this.book = book);console.log(this.book);}
我的图书服务是:
BOOKSERVICE.TS
@Injectable()导出类 BookService {私有标头 = 新标头({ 'Content-Type': 'application/json' });private bookUrl = 'http://localhost:8000/api/books/';getBook(isbn: number): Promise{const url = `${this.booksUrl}${isbn}/`;返回 this.http.get(url).承诺().then(响应 => {console.log(response.json());将 response.json() 作为 Book 返回;}).catch(this.handleError);}
当我在
中使用此 html 代码时
BookDetailComponent.html
<div class="行中心""><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>
我在 Chrome 控制台中有:
ERROR TypeError: 无法读取未定义的属性 'img_url'在 Object.eval [as updateRenderer] (BookDetailComponent.html:7)在 Object.debugUpdateRenderer [作为 updateRenderer] (core.es5.js:12822)在 checkAndUpdateView (core.es5.js:12127)在 callViewAction (core.es5.js:12485)在 execComponentViewsAction (core.es5.js:12417)在 checkAndUpdateView (core.es5.js:12128)在 callViewAction (core.es5.js:12485)在 execEmbeddedViewsAction (core.es5.js:12443)在 checkAndUpdateView (core.es5.js:12123)在 callViewAction (core.es5.js:12485)错误上下文DebugContext_ {视图:对象,节点索引:12,节点定义:对象,elDef:对象,elView:对象}
还有这个
Error: Uncaught (in promise): TypeError: Cannot read property 'img_url' of undefined类型错误:无法读取未定义的属性img_url"
每次访问该页面时,都会有 3-4 次不同的时间.有时总共有 11 个错误,有时有 19 个......
但是我的对象被正确接收,我有
XHR 加载完成: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:编号;书名:字符串;pub_date:字符串;img_url: 字符串;}
解决方案
问题在于,当您的组件 (BookDetailComponent) 呈现时,book 属性为空,因为"route: ActivatedRoute" 服务的订阅方法是异步的(了解 rxjs 的 Observables),但不返回.如果 book 属性在BookDetailComponent.html
Angular 异步管道参考: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屋!
查看全文