0

完整的 StackBlitz 示例:https ://stackblitz.com/edit/angular8-async-pipe

app组件模板中有三个相同的组件:

<app-loader></app-loader>
<app-progress></app-progress>
<app-spinner></app-spinner>

每个组件调度它自己的 NgRx 动作,它使用 NgRx 效果触发一个 Http 请求并等待其完成:

import { Component, OnInit } from '@angular/core';

import { Store } from '@ngrx/store';

import { Observable } from 'rxjs';
import { map, tap } from 'rxjs/operators';

import { ActionsService } from '../../../services/actions.service';

import * as MockyActions from '../../actions/mocky.actions';

@Component({
  selector: 'app-spinner',
  templateUrl: './spinner.component.html'
})
export class SpinnerComponent implements OnInit {
  progress$: Observable<boolean>;

  constructor (
    private store: Store<any>,
    private actionsService: ActionsService) {}

  ngOnInit() {
    this.progress$ = this.actionsService
      .isInProgress(MockyActions.GetMockySpinner)
      .pipe(
        map(({status}) => status),
        tap((status) => console.log('GetMockySpinner: ', status))
      );

    this.store.dispatch(MockyActions.GetMockySpinner());
  }
}

在使用异步管道的每个组件中,我想在 Http 请求正在进行时显示微调器:

<div class="text-center" *ngIf="!(progress$ | async); else progress">
  Spinner
</div>

<ng-template #progress>
  <div class="text-center">
    <span class="spinner spinner-sm"></span>
  </div>
</ng-template>

但在这种情况下,只有<app-spinner></app-spinner>组件中的微调器在 Http 请求过程中显示。如果应用组件模板中的组件顺序发生了变化:

<app-loader></app-loader>
<app-progress></app-progress>
<app-spinner></app-spinner>
<app-loader></app-loader>

在这种情况下,组件中的Spinner 在<app-loader></app-loader>Http 请求过程中显示。所以只有模板中的最后一个组件按预期工作。

那么Angular 8中的异步管道发生了什么变化或者我做错了什么?

完整的 StackBlitz 示例:https ://stackblitz.com/edit/angular8-async-pipe

4

2 回答 2

1

您没有为您的应用程序使用实际的状态和减速器。NgRX 要求你同时使用 action 和 reducer。您遇到的问题是,当前两个组件订阅操作主题时,第三个操作已经存在。你不会监听 NgRX 中发生的动作。相反,您要做的是观察您的状态是否被操作修改。

这是一个可以解决您的问题的有效堆栈闪电战。

https://stackblitz.com/edit/angular8-async-pipe-xexehj?file=src%2Fapp%2Fapp.module.ts

下面是一些有用的文档。 https://ngrx.io/guide/store/reducers https://ngrx.io/guide/store

于 2019-10-04T14:49:48.253 回答
0

你的 有问题MockyActions

改变

this.progress$ = this.actionsService.isInProgress(MockyActions.GetMockyProgress)
...

this.progress$ = this.actionsService.isInProgress(MockyActions.GetMockyLoader)
...

this.progress$ = this.actionsService.isInProgress(MockyActions.GetMockySpinner)

你的例子工作正常。

于 2019-10-04T14:44:14.037 回答