Angular Finalize变化检测

问题描述

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

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

[ladda]一个自定义指令,当相应的变量为true时,在按钮上显示一个加载图标;在这种情况下,变量名为isLoading。通常,我在访问服务器时会执行此操作,因此我将在访问服务器之前将isLoading设置为true,然后在返回响应时将其设置为false。

当我尝试使用rxjs管道/ finalize模式时,这会有些毛病。如果运行以下命令,则永远不会检测到更改:

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);
}

解决方法

您尝试过完整方法吗?

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