每秒钟添加一次Angular10的材料进度条值



我想每隔一秒给进度条的值加一个值,这样我就可以在进度条为100时执行一些操作。我已经写了下面的代码,但它没有任何作用。

Ts文件:

export class ProgressSpinnerTest implements OnInit {
color: ThemePalette = 'primary';
mode: ProgressSpinnerMode = 'determinate';
value = 0;
sub: Subscription;
ngOnInit(): void {
this.sub = interval(1000).subscribe(x => {
this.progressBar();
});
}
progressBar(): void {
this.value + 10;
if (this.value === 100) {
console.log("done");
this.value = 0;
}
}
}

组件:

<mat-card>
<mat-card-content>
<h2 class="example-h2">Result</h2>
<mat-progress-bar
class="example-margin"
[color]="color"
[mode]="mode"
[value]="value">
</mat-progress-bar>
</mat-card-content>
</mat-card>

我怎样才能使它每秒在进度条的值上加10?

您也可以使用rxjs运算符来完成此操作:

color: ThemePalette = 'primary';
mode: ProgressSpinnerMode = 'determinate';
progress: Observable<number>;
ngOnInit(): void {
this.progress = interval(1000).pipe(
mapTo(10),
scan((a, b) => a + b),
takeWhile((value) => value < 100, true),
map((value) => (value == 100 ? 0 : value))
);
this.progress.pipe(takeLast(1)).subscribe((_) => console.log('done'));
}

和html:

<mat-progress-bar 
[color]="color"
[mode]="mode"
[value]="progress | async">
</mat-progress-bar>

最好尽量避免在组件中使用订阅,让angular使用异步管道处理订阅。

最新更新