订阅方法内部angular 9数组为空

时间:2020-07-09 04:33:03

标签: angular rxjs subscribe

我有一个声明为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,并且为空白。但这应该是我之前添加的三个值。 此代码有什么错误?

已编辑:我还发现,在订阅方法内部,如果我将任何东西推入数组中,每次它只存储延迟值,而不存储以前的所有值。这是原始行为吗? ?

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

您要同时在Constructor和OnInit中更改数组,请注意,OnInit应该在Constructor之后修改该数组,但是订阅可能在OnInit之后发生。