angular 4 binding images cannot read property of u

2019-09-13 17:07发布

问题:

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;
}

回答1:

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



回答2:

Just add a "?" after the "book" like below. It makes the object optional and does not give error if it is not available at the time of rendering.

<div *ngFor="let book of books" class="col s12 m2">
  <div class="card">
    <div class="card-image">
      <img  src="{{book?.img_url}}" >  <!--Check this line-->
    </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>