【问题标题】:Not operation with async pipes in Angular 4在 Angular 4 中不能使用异步管道进行操作
【发布时间】:2018-07-02 04:12:30
【问题描述】:

我使用 Angular 4 作为前端来构建一个以 Node JS 作为后端的应用程序。前端将从 SQL 数据库中获取数据并显示一个表单。由于部署此提取可能需要一些时间,因此我想在提取数据时发出“请稍候”消息。现在我使用异步管道、主题和可观察对象以及一个简单的超时函数来测试它的工作原理。我试过这段代码。

在 .ts 文件中:

dataReady = new Subject<any>();
dataReadyObs = new Observable<any>();

constructor() {
  this.dataReadyObs = this.dataReady.asObservable();
}

ngOnInit() {
    someFunc() {
       setTimeout(function() {
       this.dataReady.next(true);
       }.bind(this), 2000);
    }
}

在html文件中:

<form *ngIf="dataReadyObs | async">

</form>

<h3 *ngIf="!dataReadyObs | async"> Please wait ... </h3>

但“请稍候”消息从未出现,仅在 2 秒后出现。是个 !使用管道时运算符不适用?我设法用 ng-template 解决了这个问题,但是如果需要 not 运算符,有没有办法将它与管道一起使用?

<div *ngIf="dataReadyObs | async; else waitmessage">
  <form>

  </form>
</div>

<ng-template #waitmessage>
  <h3>Please wait ...</h3>
</ng-template>

【问题讨论】:

  • 编辑代码

标签: javascript html angular


【解决方案1】:

您可以使用管道。要使其工作,您需要使用 () 编写这样的代码。因为管道是 2 操作,所以对于角度它的 'false |异步'

<h3 *ngIf="!(dataReadyObs | async)"> Please wait ... </h3>

另一种方法是使用它更安全

<h3 *ngIf="(dataReadyObs | async) === false"> Please wait ... </h3>

【讨论】:

  • 您能否详细说明为什么 BehaviorSubject 会解决问题?
  • 我正在尝试将它与组件一起使用,但是组件的 ngOnInit 调用而不等待可观察的发射
  • 这不是推荐的方法,因为 observables 通常会在订阅时发出空值,除非经过过滤,这可能会导致 ngIf 表达式错误地触发。见codelyzer.com/rules/template-no-negated-async。请改用下面@Sergei Panfilov 的答案来安全检查。
【解决方案2】:

方法如下:

<h3 *ngIf="(dataReadyObs | async) === false"> Please wait ... </h3>

因为!(dataReadyObs | async)至少会产生tslint错误

the problem with negating async

【讨论】:

    猜你喜欢
    • 2021-05-13
    • 2020-03-26
    • 1970-01-01
    • 2018-06-28
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 2017-05-05
    • 1970-01-01
    相关资源
    最近更新 更多