当第二次点击提交时才得到结果



我正在尝试在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元素

感谢

我怀疑您已经在组件装饰器中传递了changeDetection: ChangeDetectionStrategy.OnPush。在这种情况下,angular直到下一个变化检测周期才会读取这些变化,而在你的例子中,下一个变化检测周期发生在第二次点击时。

为了解决这个问题,您需要在构造函数中注入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没有害处,但解决这个问题的另一种方法是使用可观察对象和angular异步管道。

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>

这就是你的问题的原因

hasError: boolean;

您正在初始化变量,但在开始时不给出任何值。因此,一旦组件被加载,hasError的值就会变为undefined/null。所以它只会用这个值来加载模板。

如何预防:

方法1)(不推荐)

// 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. 

最新更新