Willie
Willie

Reputation: 338

Cannot force change Detection in Loading Bar Component

I'm having a tough time understanding why I cannot get a progress bar to show up correctly in my app. I have tried several things to force change detection, and to just see what is going on. Below is the scenario.

I am going through a list of Objects and formatting them, as I am going through each selected object in our system, I call the following:

this._dialog.loadingBarCurrentIndex.next(progress);

where progress is a whole number between 0 and 100.

The dialog service is pretty basic for this use, and contains the following (pertinent for this question)

public loadingBarCurrentIndex = new Subject<any>();
public _loadingBarCurrentIndex$ = this.loadingBarCurrentIndex.asObservable();

I subscribe to this observable in my "transition-loader" component like so:

currentIndexSub: Subscription;
...
constructor(
    private _dialog: DialogService
) {
    this.currentIndexSub = this._dialog._loadingBarCurrentIndex$.subscribe(res => {
        this.loadingBarCurrentIndex = res;
        console.log(this.loadingBarCurrentIndex); //Shows loading values in real time...
    });
}

So far so good. I can console log res here and see it changing from 0 to 100 over the course of however long the calling function is executing.

My question is, why can't I get this value to update in my template? I have tried the following:

  1. Forcing the current index to run inside of ngZone.run()
  2. Setting this.loadingBarCurrentIndex value inside of a setTimeout function to force change detection
  3. actually putting something like this.cd.detectChanges() after I try and assign the new value as well.

None of these methods work, though I can see the value clearly changing in the console. Nevermind any question about the component, considering at this point all I have in there is:

<p>{{loadingBarCurrentIndex}}</p>

Any ideas on what I might do differently? Whatever I do seems to not make a difference.

Upvotes: 0

Views: 366

Answers (1)

Kamran Khatti
Kamran Khatti

Reputation: 4127

If you need progressbar progress percentage in template then there is not need to subscribe all you need to return the Observable and use that in template by using async pipe, checkout the following.

 // Initialize current index as Observable 
 loadingBarCurrentIndex$: Observable<number>; 

 // Assign the current index response to Observable (do not subscribe)
 this.loadingBarCurrentIndex$ = this._dialog._loadingBarCurrentIndex$;

Now in template use async pipe to subscribe the current index Observable (async pipe will unsubscribe automatically so no need to unsubscribe manually).

<p>{{ loadingBarCurrentIndex$ | async }}</p>

Hope this solve your problem.

Upvotes: 0

Related Questions