错误TypeError:无法读取未定义的属性'poster_path'

时间:2018-10-14 15:19:22

标签: angular typescript

我更新了代码。我认为我做错了,但我不在哪里。

我尝试了很多事情,但我听不懂。 我有此错误,但我不知道如何解决 请帮助我

import { StorageService } from '../services/storage.service';
import { Component, Input, OnInit } from '@angular/core';

@Component({
  selector: 'app-movies',
  templateUrl: './movies.component.html',
  styleUrls: ['./movies.component.css']
})
export class MoviesComponent implements OnInit {
  @Input() movie;
  movieDetails = {};
  imgBaseUrl: string;
  posterUrl: string;
  display = false;
  displayButton = 'Display details';

  constructor(
    private storage: StorageService,
  ) { }

  ngOnInit() {
    if (this.movie.poster_path) {
      this.posterUrl = 'http://via.placeholder.com/154x218?text=Not+avaliable';
    } else {
      this.imgBaseUrl = this.storage.getImageBaseUrl()
      this.posterUrl = this.imgBaseUrl + 'w154' + this.movie.poster_path;
    }
  }

  changeButton() {
    this.display = !this.display;
    if (this.display === true) {
      this.displayButton = 'Hide details';
    } else {
      this.displayButton = 'Display details';
    }
  }
}

error

2 个答案:

答案 0 :(得分:1)

这肯定可以工作

ngOnInit() {
  if (this.movie && this.movie.poster_path) {
    this.imgBaseUrl = this.storage.getImageBaseUrl()
    this.posterUrl = this.imgBaseUrl + 'w154' + this.movie.poster_path; 
  } else {
    this.posterUrl = 'http://via.placeholder.com/154x218?text=Not+avaliable';
  }
}

答案 1 :(得分:0)

当您的this.movie运行时,

undefinedngOnInit(),因为异常告诉您。

您可以这样检查:

ngOnInit() {
  if (this.movie && this.movie.poster_path) {
    this.posterUrl = 'http://via.placeholder.com/154x218?text=Not+avaliable';
  } else {
    this.imgBaseUrl = this.storage.getImageBaseUrl()
    this.posterUrl = this.imgBaseUrl + 'w154' + this.movie.poster_path;
  }
}

那应该触发您的else条件。