Angular2 http observables - 如何使用未定义的类型

标签 angular angular2-services

我正在将一些代码从 Angular1 迁移到 Angular2,但遇到了一些问题。我可以打开 json 响应、填充模板并从模板 ng 函数访问数据,但无法直接从组件类访问数据。从我读过的内容和看到的错误消息来看,Angular2 http/observable 似乎没有返回纯 json 对象,所以我怀疑我需要重新映射它,但不确定如何。我相信使用 onPromise 也应该可以回溯到 promise ,但还没有成功。我花了很多时间在谷歌上搜索解决方案,并尝试实现其中的大部分,但没有运气。如果有人可以建议如何将响应重新映射为可用格式或直接访问响应中的数据,我们将不胜感激。

来自服务的 http 调用示例:-

getExam() {
    return this._http.get('/json/exam.json')
      .map(data => data.json());
  }

订阅示例:-

  ngOnInit() {
      this._examsService.getExam()
        .subscribe(response => this.exam = response);
    console.log(this.exam.length);  //this fails
  }

控制台日志错误示例:-

TypeError: Cannot read property 'length' of undefined in [null]

示例数据结构(非常简化测试):-

{"title":"My Practice Exam",
  "questions":[
    {"question":"1+1 = ",
      "answers":[
        {"answer":"2","correct":"Y","selected":"N","iscorrect":""},
        {"answer":"5","correct":"N","selected":"N","iscorrect":""}]},
    {"question":"2+2 = ",
      "answers":[
        {"answer":"4","correct":"Y","selected":"N","iscorrect":""},
        {"answer":"7","correct":"N","selected":"N","iscorrect":""}]},
    {"question":"3+3 = ",
      "answers":[
        {"answer":"6","correct":"Y","selected":"N","iscorrect":""},
        {"answer":"8","correct":"N","selected":"N","iscorrect":""}]}]}

在 Angular1 中,我能够直接从函数访问数据 - 例如如下,并且希望在 Angular2 中执行类似的操作

if ($scope.myExams[0].questions[q].answers[a].correct == 'y') ...

最佳答案

使用此代码

ngOnInit() {
  this._examsService.getExam()
    .subscribe(response => this.exam = response);
  console.log(this.exam.length);  //this fails
}

第一行发送请求 this._examsService.getExam() .subscribe(...) 并注册对响应的兴趣,然后控制台。 log(this.exam.length)执行完毕,但是此时respone => this.exam = response还没有执行,因为getExam() code> 尚未完成与服务器的连接并接收响应。

您需要留在事件链中才能处理最终返回的数据,例如:

ngOnInit() {
  this._examsService.getExam()
    .subscribe(response => {
      this.exam = response;
      console.log(this.exam.length);  //this shoudn't fail anymore
    });
}

我不知道这是否能解决您的问题,但您的问题没有提供有关您对更详细的解决方案的要求的足够信息。

关于Angular2 http observables - 如何使用未定义的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34925882/

相关文章:

javascript - Angular 2 beta.8 如何使用@Query?

包含 bool 值的 Angular Material mat-table 过滤器 mat-table 列

javascript - 根据变量angular生成动态css

angular - 强制服务销毁?

javascript - 调用 http 函数时不会触发 XHR 请求

Angular 6 在 "e2e/app"文件夹中生成服务

javascript - Angular 2 : In ngModelChange function how to compare old and new values of ngModel?

angular - 如何在angular2中等待用户点击事件?

Angular 2 Header组件标题根据状态动态变化

typescript - Angular 2 服务没有被注入(inject)到组件中