Home > Mobile >  ngFor not update template and code in combineLatest run many times
ngFor not update template and code in combineLatest run many times

Time:12-11

I have a template

<div *ngFor="let item of list">
   {{item.name}}
</div>

Then in ts code.

ngOnInit() {
   const s0 = this.service.getList(this.id);
   const s2 = this.service.getOthers(this.id);
   combineLatest([s0, s1]).subscribe(([r0, r1]) => {
       this.list = r0;
       console.log('service is called');
   }
}

In another place, I have a button click event to add a new item to the list.

addItemToList(item: any) {
    this.service.addItem(item).subscribe(
        value => {
           console.log(value);
           //  then reload page by calling get list again
           this.service.getList(this.id).subscribe(
              res => this.list = res; // I want to refresh the view by this new list
              console.log(res);
             );
        }
     );
}

I am sure I added the new item successfully. But the view is not updating and the line console.log('service is called') in combineLatest was called many times. So the list is still the value when first time loading.(this.list = r0)

I can only update the view by click F5. I have tried ngZone or ChangeDetectorRef. Just not working....

CodePudding user response:

It looks like you're trying to output two responses from your subscribe in

   combineLatest([s0, s1]).subscribe(([r0, r1]) => {
       this.list = r0;
       console.log('service is called');
   }

I think you need to have one response from your subscribe. Then split it after like:

   combineLatest([s0, s1]).subscribe(res => {
       this.list = res;
       ***split data***
       console.log('service is called');
   }

However if you want to differentiate the two observables you may have to nest their data in an object as when they are combined they will be returned as one response. Or you may not want to use combineLatest as it combines them.

CodePudding user response:

I figured it out by myself. Just add take(1)

Before:

combineLatest([s0, s1]).subscribe(([r0, r1])

After:

combineLatest([s0, s1]).pipe(take(1)).subscribe(([r0, r1])
  • Related