【问题标题】:Array from shared service has output but returns undefined来自共享服务的数组有输出但返回未定义
【发布时间】:2019-01-03 18:38:56
【问题描述】:

从共享服务返回数组的组件

export class QuestionsComponent implements OnInit {
_questions: any;
constructor(private apiService: ApiService) {
  this._questions = this.apiService._dataArray

}
}

使用哪个输出

{{ this._questions | json}}
在 html 组件中
[
  [
    {
       "foo": "bar",
        ... so on
    }
  ]
]

但是当使用控制台输出数组时都返回未定义

ngOnInit(): void {
  console.log(this._questions[0])
console.log(this._questions)
}

数组在被另一个组件的事件触发时被收集

其他组件:

  <input type="checkbox"  [(ngModel)]="option.checked" (ngModelChange)="UpdateData()"/>
  UpdateData(){
    this.apiService.getFilters(this._filters);
  }

API 服务

 _dataArray: any[] = [];
 getFilters(object){
  this._dataArray.length = 0;
  this._dataArray.push(object);
}

【问题讨论】:

  • 这不应该是这样的。能否提供更多信息
  • 将控制台日志放入构造函数中,看看会发生什么。也尝试在浏览器中进行调试。也可以在超时后尝试。这样你可能会找到线索
  • 同样的事情,实际上数据是在另一个组件发生事件时收集的,参见编辑代码

标签: javascript arrays json angular typescript


【解决方案1】:

这是因为你的构造函数中的代码在ngOnInit之前执行。试试这个吧:

ngOnInit(): void {
  this._questions = this.apiService._dataArray
  console.log(this._questions[0])
  console.log(this._questions)
}

【讨论】:

  • console.log(this._questions[0]) 返回未定义,而 console.log(this._questions) 不返回任何内容
猜你喜欢
  • 2017-06-08
  • 1970-01-01
  • 2020-10-09
  • 2018-06-26
  • 2021-11-29
  • 1970-01-01
  • 2015-12-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多