【问题标题】:Angular passing data to variable and that variable usage角度将数据传递给变量以及该变量的使用
【发布时间】:2020-09-18 17:29:44
【问题描述】:

声明变量

export class TestComponent implements OnInit {
testVar:string;

然后初始化

ngOnInit() {

this.somefunction works.subscribe( 
this.testVar='testData';
console.log('log1 '+this.testVar);
);
console.log('log2 '+this.testVar);
}

现在触发 AfterViewInit:

ngAfterViewInit() {
console.log('log3 '+this.testVar);

结果是

log1 testData
log2 undefined
log3 undefined

问题是为什么 log2 和 log 3 给出未定义的 testVar,我该如何解决?

【问题讨论】:

标签: angular variables initialization ngoninit


【解决方案1】:

这不是异步数据的工作方式。一旦调用,变量就不会被赋值。所有直接依赖异步数据(此处为this.testVar)的语句都应该在订阅中。

ngOnInit() {
  this.service.someFunction().subscribe(
    value => {
      this.testVar='testData';
      console.log('log1 '+this.testVar);
      console.log('log2 '+this.testVar);
      ...
    }
  );
}

AfterViewInit 生命周期钩子与控制器中变量的初始化方式无关。它将在 Angular 完全初始化组件的视图/模板后调用。

有关如何访问异步数据的更多详细信息,请参见此处:https://stackoverflow.com/a/14220323/6513921

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-03
    • 2015-09-22
    • 2017-09-17
    • 1970-01-01
    • 1970-01-01
    • 2023-01-08
    • 1970-01-01
    相关资源
    最近更新 更多