代码之家  ›  专栏  ›  技术社区  ›  Dino

一旦父函数在forEach中完成可观测项,则角度触发子函数

  •  0
  • Dino  · 技术社区  · 7 年前

    在父组件中,我将观察到的响应推送到一个数组,我将该数组传递给子组件。

    parent.component.ts

    let categoriesArr = [];
    
    for (let category of listing.categories) {
          this._projectService.getCategories().subscribe((data) => {
                 this.categoriesArr.push(data);
           });
    }
    

    parent.component.html

    <child-comp #childComp [categories]="categoriesArr"></child-comp>
    

    在子组件中,我想在父函数中完成for循环后调用一个特定的函数。

    @Input() public categories;
    
    public limitCategories() {
    **//I want to call this function from parent once the for loop with observables is finished**
    ...
    }
    

    child.component.html

    <div class="Category" *ngFor="let item of categories">
    ...
    </div>
    

    我尝试将categoriesArr设置为可观察的,然后在子组件中订阅它,但之后我会调用 limitCategories() 每次都有变化。我只想在最后一次呼叫服务后再呼叫一次。

    2 回复  |  直到 7 年前
        1
  •  1
  •   Harun Yilmaz    7 年前

    你可以用 @ViewChild 将子引用作为 ChildComponent :

    @ViewChild('childComp', {read: ChildComponent})
    childComp: ChildComponent;
    

    然后在循环中,您可以调用 limitCategories() 方法:

    for (let category of listing.categories) {
      this._projectService.getCategories().subscribe((data) => {
             this.categoriesArr.push(data);
    
             this.childComp.limitCategories();
    
       });
    }
    

    更新

    在上次异步操作之后,您可以使用 async/await 等待操作完成。

    parent.component.ts

    ngOnInit(){
      this.getCategories();
    }
    
    
    getCategories = async () => {
        for (let category of listing.categories) {
           await this._projectService.getCategories().toPromise().then((data) => 
           {
               this.categoriesArr.push(data);
           });
        }
    
        this.childComp.limitCategories();
    
    }
    
        2
  •  0
  •   user4676340 user4676340    7 年前

    forkJoin 接线员:

    const calls$ = listing
      .categories
      .map(category => this._projectService.getCategories(category))
    
    forkJoin(calls$).subscribe(data => {
      this.categoriesArr = [...data];
      this.childComp.limitCategories();
    })
    

    分叉连接 将调用子方法。

    推荐文章