首页 > 解决方案 > Angular 完成变更检测

问题描述

我在组件的 HTML 中定义了以下内容:

<button mat-button type="submit" [disabled]="invalidEmail" [ladda]="isLoading">Reset Password</button>

其中[ladda]是一个自定义指令,当相应变量为真时,该指令会在按钮上显示加载图标;在这种情况下,变量名为isLoading。通常我在访问服务器时会这样做,所以我会在isLoading访问服务器之前设置为 true,然后在返回响应时将其设置为 false。

当我尝试使用 rxjs 管道/终结模式时,这会变得有点麻烦。如果我运行以下命令,则永远不会检测到更改:

this.passwordService.resetPassword(input)
    .pipe(finalize(() => this.isLoading = false))
    .subscribe(
        () => this.success = true,
        err => this.error = JSON.stringify(err)
    );

我必须手动调用 NgZone::run 才能使其工作:

this.passwordService.resetPassword(input)
    .pipe(finalize(() => this.ngZone.run(() => this.isLoading = false)))
    .subscribe(
        () => this.success = true,
        err => this.error = JSON.stringify(err)
    );

这是为什么,我做错了吗?

更新- 每个请求,这里是 resetPassword 方法:

resetPassword(reset: IPasswordReset): Observable<void> {
    const url = `${environment.ApiUrl}/Api/UserProfile/ResetPasswordFromToken`;
    const options = new HttpOptions();
    options.headers = new HttpHeaders();
    options.headers = options.headers.append('Content-Type', 'application/x-www-form-urlencoded');
    return this.http.post(url, reset, null, options);
}

标签: rxjsangular9

解决方案


你试过完整的方法吗?

this.passwordService.resetPassword(input)
    .subscribe(
        () => this.success = true,
        err => this.error = JSON.stringify(err),
        () => this.isLoading = false
    );

推荐阅读