【问题标题】:Cannot read property of undefined Angular 4 Typescript无法读取未定义的 Angular 4 Typescript 的属性
【发布时间】:2018-05-09 23:13:24
【问题描述】:

我已经尝试解决这个问题一段时间了,肯定可以使用一些帮助。 我正在尝试显示从服务器获得并存储在本地的问题。但是当我尝试显示我得到的问题时,它给了我以下错误:

Cannot read property 'question' of undefined

这是我的 HTML

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Questionnaire</title>
</head>
<body>
<div class="container" id="Question" align="center">
 <h2 [innerHTML] = "q.question"></h2>
</div> 


</body>
</html>

这是肯定会返回值的打字稿,因为我可以记录它们,所以我检查了:

@Component({
  selector: 'app-new-questionnaire',
  templateUrl: './new-questionnaire.component.html',
  styleUrls: ['./new-questionnaire.component.css'],
  providers: [NewServerRequestsService]
})

export class NewQuestionnaireComponent implements OnInit {



  q: any;
  sub: any;
  id: number;
  cQuestion: number;
  score: number;
  qNumber: number;

  constructor(private serverService: NewServerRequestsService, private 
route: ActivatedRoute, private router: Router){} 


  static questionTime = performance.now();  
  onload()
  {
    console.log(NewQuestionnaireComponent.questionTime);
    // this.ButtonClicks();    
  }

  ngOnInit() {
    this.sub = this.route.params.subscribe(params => {
      // (+) converts string 'id' to a number
      // fetch the file and get next Question
      this.id = +params['id'];

      if (localStorage.getItem('q') !== null) {
        var data = JSON.parse(localStorage.getItem('q'))
        this.qNumber = parseInt(localStorage.getItem('qNumber'))
        this.q = data.results[this.id - 1]
      } else {
        this.serverService.getQuestion()
        var data = JSON.parse(localStorage.getItem('q'))
        this.qNumber = parseInt(localStorage.getItem('qNumber'))
        this.q = data.results[this.id - 1]
      }

    });
  }

    }

  }

这里是服务:

@Injectable()
export class NewServerRequestsService {

  constructor(private http: Http) { }

  getQuestion()
  {
    return this.http.get("https://opentdb.com/api.php?amount=30")
    .map(res => res.json()).subscribe(
    data => {
        // shuffle questions
        for (var i = 0; i < data.results.length - 1; i++) {
            var j = i + Math.floor(Math.random() * (data.results.length - 
i));

            var temp = data.results[j];
            data[j] = data.results[i];

            data[j].incorrect_answers.push(data[j].correct_answer)

            data[i] = temp;

        }
        localStorage.setItem("q", JSON.stringify(data))
        localStorage.setItem("qNumber", JSON.stringify(data.length))
    },
    err => console.error(err)
    )

}

}

这里是获取数据的地方:

  @Component({
  selector: 'home',
  templateUrl: 'home.component.html',
  providers: [NewServerRequestsService]
})

export class HomeComponent implements OnInit, OnDestroy {

  constructor(private QuizService: NewServerRequestsService, private route: 
ActivatedRoute, private router: Router) {

  }

  ngOnInit() {
    this.QuizService.getQuestion();
  }
  ngOnDestroy() { }

}

【问题讨论】:

  • 尝试删除所有非必要代码,以提供重现您的问题的最小示例。这样一来,人们就更有可能尝试帮助您,并且该问题对有类似问题的其他人也更有帮助。
  • 您(至少)在模板和 TS 中遇到了一些异步问题。调用this.serverService.getQuestion() 时,您无法确定在获取数据时是否在localStorage 中设置了数据:var data = JSON.parse(localStorage.getItem('q')) 在您的else 中。我 99% 确定数据不存在。请阅读此:stackoverflow.com/questions/43055706/… 和此:stackoverflow.com/questions/34734671/… 以了解异步性。
  • @dskrvk 感谢您告诉我。我已经去掉了不必要的东西。
  • @AJT_82 我做了一些修改。请通过同样的方式。
  • @AJT_82 是正确的,这是异步的问题。渲染 dom 时,q 尚未定义。

标签: html json angular typescript data-binding


【解决方案1】:

这个错误是因为q在渲染视图时未定义,尝试使用?进行安全导航:

<h2 [innerHTML] = "q?.question"></h2>

【讨论】:

  • 什么都没出现。我的意思是没有错误,但毫无疑问。请让我知道这意味着什么。谢谢
  • 当你使用安全导航时:q?.question,意思是:检查q是否不是undefined,然后在q中寻找question
【解决方案2】:

初始化 q: any = {} 如果是对象,[] 如果是数组;) 现在告诉我 console.log(q) 显示什么

在您的 ts 或您的 html 中检查 q &lt;h2 *ngIf="q" ...

【讨论】:

  • 它说未定义
  • 好的,所以您永远不会获取或更改获取数据的组件中的值,当您获取它们时,它是异步的,因此您必须验证它是否存在并创建一个可以显示的空对象,直到您获取数据 ;) 然后尝试 q = this.QuizService.getQuestion(); si 你可以使用 q 并显示它:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-26
  • 2023-01-15
  • 1970-01-01
  • 2018-04-12
  • 2018-02-07
相关资源
最近更新 更多