如何使用Angular 6获取ForEach Loop和SetTimeout

时间:2018-10-25 02:13:10

标签: angular

我知道以前可能会问过这个问题,但是我在这里搜索的大多数主题都无法解决我的问题。

我有要移到 angular 6 angularjs 代码。我只想从下面的 angularjs 代码

来在 angular6 中实现Foreach循环

Angularjs代码

                 setTimeout(function() {
                        $scope.$apply(function(){


                        angular.forEach(res.data,function(item) {
                            $scope.crud_s.push(item);
                        });  

                        });
                    },500); 

这是我在angular6中尝试过的

      getRecord(): void {
    this.crudService.getAll().subscribe(
        res => {
            this.crud_s = res;

// starting code issue


                                 setTimeout(function()=>{ 
                                    this.$apply(function(){ 

                                    angular.forEach(this.crud_s,function(item) {
                                       this.crud_s.push(item);
                                    }); 

                                    });
                                },500); 

    //end code issue

    //more codes will continues
     }

2 个答案:

答案 0 :(得分:1)

Angular6没有可用的angular.forEach,您需要使用for循环。另外,您尝试将同一项目推送到同一数组,请确保变量不同。

for(let item of this.crud_s){
  this.crud_s.push(item);  //this.crud_s should be new array
}

答案 1 :(得分:1)

Angular 6使用Typescript作为基本语言,因此您需要使用ts syntex编写代码。对于“ forEach”外观,您可以编写

let myArray = [1,2,3,4,5];
myArray.forEach((item) => {
  console.log(item);
});

和setTimeOut将像这样:

setTimeout(() => { //enter your forEach loop here }, 1000);

此外,您在这里不需要$ apply和$ digest。 Angular在这里提供了不同的生命周期挂钩。希望对您有帮助。