无法读取未定义角度6的属性“图像”

Ahm*_*awy 0 undefined typescript angular

尝试获取详细信息时,它会呈现给dom,但会给出未定义的错误。这是要显示的图像

在此处输入图片说明

这是书籍详细信息组件

export class BookDetailsComponent implements OnInit {
  book: Book;
  books: Book[];
  id: string;

  constructor(private route: ActivatedRoute, private booksService: BooksService, private http: Http) { }

  async getAsyncData() {
    this.books = await this.http.get('/assets/books.json').toPromise().then(
      data => this.books = data.json().books
    );
    this.book = this.books.filter(book => book.id === this.id)[0];
  }

  ngOnInit() {
    this.route.params.subscribe(
      (params: Params) => {
        this.id = params['id'];
        if (this.book) {
          this.book = this.booksService.getBook(this.id);
        } else {
          this.getAsyncData();
        }
      }
    );
  }

}
Run Code Online (Sandbox Code Playgroud)

这是来自服务的getBook函数

getBook(id: string) {
    return this.books.filter(book => book.id === id)[0];
  }
Run Code Online (Sandbox Code Playgroud)

fjc*_*fjc 6

这样做的问题通常是您使用诸如

<img src="{{ book.image }}" />
Run Code Online (Sandbox Code Playgroud)

在您的代码中。首次渲染组件时,您的book对象仍未定义(请参见book: Book;:此处没有值定义)。

一种解决方案是将对book的引用包装在*ngIfed块中:

<ng-container *ngIf="book">
    <img src="{{ book.image }}" />
</ng-container>
Run Code Online (Sandbox Code Playgroud)

或者,或者,如果仅是单个图像,请执行

<img src="{{ book.image }}" *ngIf="book" />
Run Code Online (Sandbox Code Playgroud)

或者,如果您不介意img在您的DOM中使用空src:

<img src="{{ book?.image }}" />
Run Code Online (Sandbox Code Playgroud)