【问题标题】:Getting result only when click submit for second time仅在第二次单击提交时才获得结果
【发布时间】:2021-05-30 09:22:01
【问题描述】:

我正在尝试在 Angular 7 中更改密码功能,

从后端,如果当前密码不正确,则返回true。

并且会出现角度错误信息。

但问题是我必须单击两次才能显示错误消息,即使我可以在打印真实值的日志中看到响应,但不确定为什么 *ngIf 不起作用

模板端

    <span *ngIf="hasError">
         wrong current password value  
    </span>

我的组件端

hasError: boolean;

 submit () {
     this.apiService
    .changePassword(this.formGroup.value).subscribe(res => {
  console.log(res);
  this.hasError = res;    });

服务端

  changePassword(body: any){
     return this.http.post<any>(this.url + 'changePassword', body);
  }

谁能解释为什么我必须点击提交按钮两次才能显示 html 元素

谢谢

【问题讨论】:

    标签: angular typescript rxjs angular-services angular-changedetection


    【解决方案1】:

    我怀疑你在组件装饰器中传递了changeDetection: ChangeDetectionStrategy.OnPush。在这种情况下,角度将不会读取更改,直到下一个更改检测周期(在您的情况下发生在第二次单击时)。

    为了解决这个问题,您需要在构造函数中注入ChangeDetectorRef 并手动调用更改检测循环。比如:

      constructor(private cdr: ChangeDetectorRef) {}
      
      hasError: boolean;
    
      submit () {
         this.apiService
        .changePassword(this.formGroup.value)
        .subscribe(res => {
           console.log(res);
           this.hasError = res;    
           this.cdr.markForCheck();  // <<<---- detect changes
      });
    

    虽然使用 ChangeDetectorRef 并没有什么坏处,但解决此问题的另一种方法是使用可观察对象和角度异步管道。

      hasError$: new Subject();
    
      submit () {
        this.apiService
        .changePassword(this.formGroup.value)
        .subscribe(res => this.hasError$.next(res));
    

    在模板中:

      <span *ngIf="hasError$ | async">
           wrong current password value  
      </span>
    

    【讨论】:

    • 感谢您的帮助,但我们认为还有其他方法可以重写我的代码以在推送时达到 changeDetection 吗?
    【解决方案2】:

    这是您的问题的原因

    hasError: boolean;

    您正在初始化变量,但在开始时没有给出任何值。所以一旦组件被加载,hasError 的值就是 undefined/null。所以它只会加载具有该值的模板。

    如何预防:

    方法一)(非首选)

    // If you dont want to initiate the value in the component.ts file, make this change in 
      the HTML file, 
    
    <span *ngIf="!!hasError">
             wrong current password value  
    </span>
    
    
    the '!!' will check for null status of the variable 
    

    方法2)首选

    // Initiate the value of the variable to false, 
    
    // In component.ts file
    
    hasError: boolean = false; // IMPORTANT
    
    and then your code remains the same. 
    
    So the initial value will now be false, and also when the service is subscribed, you can have it true or false and your HTML also remains the same. 
    
    

    【讨论】:

      猜你喜欢
      • 2017-07-28
      • 1970-01-01
      • 1970-01-01
      • 2019-10-28
      • 1970-01-01
      • 2017-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多