使用array.push()创建的数组具有元素,但无法使用angular。

28 浏览
0 Comments

使用array.push()创建的数组具有元素,但无法使用angular。

我有两个Array。其中一个拥有初始元素,另一个通过array.push()ngOnInit中添加元素。最后,两者都有输出的元素,但HTML没有渲染使用.push添加的元素。

代码:

newObj;
error;
myObjects: Array = [];
itsObjects: Array = [
  {
    id: '1',
    title: 'title 1'
  },
  {
    id: '2',
    title: 'title 2'
  },
  {
    id: '3',
    title: 'title 3'
  }
];
ngOnInit() {
  this.subscription = this.mys.myService().subscribe(
    res => {
      this.newObj = res,
      this.myObjects.push(
          {
            id: element.id,
            title: element.title
          }
        )
    },
    error => this.error = error,
  )
}

解决方案

主要注意的是在forEach之后的this.myObjects = this.tmpObj,它收集所有元素以传递到ngOnInit范围之外,我修改了我的代码如下:

servicOutput; //获取数据
tmpObj: Array = []; //作为临时数据管理
myObjects: Array = []; //用于收集所有元素到HTML
error;
ngOnInit() {
  this.subscription = this.mys.myService().subscribe(
    res => {
      this.servicOutput = res,
      this.servicOutput.forEach(element => {
        this.pushFunc(element);
        }
      ),
      this.myObjects = this.tmpObj; //在这里将所有元素收集为一个对象,并传递到ngOnInit范围之外
    },
    error => this.error = error,
  )
}
pushFunc(element) {
  this.tmpObj.push(
    {
      id:    element.id,
      title: element.title
    }
  )
}

0
0 Comments

问题的原因是在使用array.push()方法创建的数组中,元素无法在Angular中使用。这可能是因为this.tmpObj中的数据无法直接赋值给this.myObjects导致的。

解决方法是使用数组的slice()方法。通过this.myObjects = this.tmpObj.slice()this.tmpObj中的数据复制到this.myObjects中。这样做的目的是创建一个新的数组,其中包含this.tmpObj中的所有元素,并将其赋值给this.myObjects

以下是解决问题的代码示例:

this.myObjects = this.tmpObj.slice();

通过使用slice()方法,我们可以确保this.myObjects中的元素可以在Angular中正常使用,解决了无法使用array.push()创建的数组的问题。

0
0 Comments

在Angular中,数组内部的更改不会被自动检测到,它只会在数组本身的引用发生更改时进行检测。为了让HTML重新渲染,需要使用以下方法之一来通知Angular发生了变化。

方法1 - 使用rest/spread运算符代替push来更改数组:

this.myObjects = [...this.myObjects, this.newObj[0]];

方法2 - 使用rest/spread运算符在push之后更改数组引用:

this.myObjects.push(this.newObj[0]);
this.myObjects = [...this.myObjects];

方法3 - 使用JSON.stringify/parse在push之后更改数组引用:

this.myObjects.push(this.newObj[0]);
this.myObjects = JSON.parse(JSON.stringify(this.myObjects));

方法4 - 使用detectChanges()通知Angular发生了变化:

constructor(private changeDetectorRef: ChangeDetectorRef) { }
public testMethod() {
    this.myObjects.push(this.newObj[0]);
    this.changeDetectorRef.detectChanges();
}

以上是解决"Array made by array.push() has elements but couldn't use angular"问题的几种方法。通过使用上述方法,可以确保Angular能够正确检测到数组的更改,并重新渲染HTML。

0
0 Comments

Angular的变更检测机制无法处理数组内容的变更。解决方法有两种:一种是像之前评论中建议的那样改变数组的引用;另一种是实现自己的ngDoChange方法,以便可以实现自己的方式来检测数组内容的变化。

你可以参考这个答案来进一步了解如何实现ngDoChange:https://stackoverflow.com/a/42962723/11420760

我的代码可以捕获元素并将其推入数组中,我有所有元素都在数组中,但无法使用它们并渲染出来。

我看不到xdecdec的评论,所以不知道它指的是什么。也许已经被删除了。

0