【问题标题】:angular 9 array is empty inside subscription methodangular 9 数组在订阅方法中为空
【发布时间】:2020-07-09 04:33:03
【问题描述】:

我有一个声明为 public 并初始化为空数组的数组。

correctives = [];

现在在构造方法里面我初始化了订阅方法

constructor(private messageService: MessageService){
    this.childTicketSubscribe = this.messageService.getChildTicketData().subscribe((data) => {
        console.log(JSON.stringify(this.correctives)); //[]
        // print empty array
    });
}

现在我在 OnInit 方法中初始化它

ngOnInit() {
  this.correctives = [{value: ''}];
}    

现在我有两种方法: 1 向数组中添加数据

addCorrective() {
    this.correctives.push({value: ''});
}

另一个调用另一个组件并且来自另一个组件的数据正在进入订阅方法。

所以当我将三个数据添加到数组中,然后单击另一个函数从其他组件获取数据。在订阅方法中获取数据后,我打印this.correctives,它是空白的。但它应该是我之前添加的三个值。 这段代码有什么错误?

已编辑:另外我发现,在订阅方法里面,如果我 push 任何东西在一个数组里面,每次它只存储最新的值,而不是之前的所有值。这是原来的行为吗?

【问题讨论】:

  • 无法判断您提供的代码发生了什么。创建一个可以重现您的问题的 StackBlitz。

标签: angular rxjs subscribe


【解决方案1】:

您能否在 ngAfterViewInit 方法中添加您的订阅代码。

ngAfterViewInit() {
this.childTicketSubscribe = this.messageService.getChildTicketData().subscribe((data) => {
        console.log(JSON.stringify(this.correctives)); //[]
        // print empty array
    });
  }

【讨论】:

    【解决方案2】:

    您在 Constructor 和 OnInit 中都更改了数组,因此 OnInit 应该在 Constructor 之后修改数组,但订阅可能发生在 OnInit 之后。

    【讨论】:

    • 我还在一个名为“addCorrective”的函数中对其进行了修改。一切正常,但在订阅方法中它是空白的
    • 因为构造方法会在ngOninit方法之前执行,所以它会是空白的,所以在声明你的数组时尝试在组件内部进行初始化!
    • 这里最简单的解决方案是将您的订阅代码移动到 OnInit
    猜你喜欢
    • 2020-10-11
    • 1970-01-01
    • 2020-11-16
    • 1970-01-01
    • 2020-07-06
    • 1970-01-01
    • 1970-01-01
    • 2020-09-17
    • 1970-01-01
    相关资源
    最近更新 更多