在我的角度应用程序中,我想显示来自HTTP请求的记录的动画计数。我使用RxJ,但是响应返回得非常快,我只看到了请求的最终结果。我试图增加clientsCount并将其显示在视图中。我怎样才能放慢一点速度,这样就可以看到,随着请求的进行,数量是如何逐渐增加的。
this.clients$ = this.clientService.getClients()
.pipe(
tap(e => console.log(e)),
map(clients => {
return clients
.map((client) => { this.clientsCount++; return client })
}),
finalize(() => { this.isLoading = false; console.log('HJJHJG') }),
catchError((err) => { this.isLoading = false; throw err }));
发布于 2022-01-24 07:10:09
在这里,让我来整理一下您的代码:
this.clients$ = this.clientService.getClients().pipe(
tap(console.log),
tap(clients => clients.forEach(client => this.clientsCount++)),
finalize(() => { this.isLoading = false; console.log('HJJHJG') }),
tap({error: err => this.isLoading = false})
);
您可能会注意到一些有趣的东西,您使用的所有操作符都不预先形成任何转换(RxJS的基本功能)。他们都只会产生副作用。
让我们看一看这一行代码:
clients.forEach(client => this.clientsCount++)
此循环将同步运行。这在语义上与以下内容相同:
this.clientsCount += clients.length
我不知道你想慢点什么。
this.clientService.getClients()
是否会发出多个客户端数组?您可以在zip
和timer
中这样扩展:
const clientService$ = this.clientService.getClients().pipe(
tap(console.log),
tap(clients => this.clientsCount += clients.length),
finalize(() => { this.isLoading = false; console.log('HJJHJG') }),
tap({error: err => this.isLoading = false})
);
this.clients$ = zip(clientService$, timer(0,1000)).pipe(
map([cs] => cs) // Remove timer info
);
如果要将客户端数组转换为客户机流,可以这样做:
this.clients$ = this.clientService.getClients().pipe(
tap(console.log),
concatMap(clients => zip(clients, timer(0,1000)),
map([cs] => cs), // Remove timer info
tap(() => this.clientsCount++),
finalize(() => { this.isLoading = false; console.log('HJJHJG') }),
tap({error: err => this.isLoading = false})
);
https://stackoverflow.com/questions/70833141
复制