Javascript http请求后角度模板未更新
在我发出POST请求后,我无法更新我的角度模板 以下是组件:Javascript http请求后角度模板未更新,javascript,angular,Javascript,Angular,在我发出POST请求后,我无法更新我的角度模板 以下是组件: import { HttpClient } from '@angular/common/http'; @Component({ selector: 'example', templateUrl: './example', changeDetection: ChangeDetectionStrategy.OnPush }) export class ExampleComponent implements AfterVi
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'example',
templateUrl: './example',
changeDetection: ChangeDetectionStrategy.OnPush
})
export class ExampleComponent implements AfterViewInit, OnInit {
public mailResult: String;
constructor(private apiService: ApiService) {
this.mailResult = 'notsent'; //updating in template
}
onSubmit() {
this.mailResult = 'pending'; // updating in template
this.apiService.testPostRequest().subscribe((res)=>{
console.log("res", res); // working fine loging res
this.mailResult = 'requestsucess'; // not update in template
});
}
}
这就是模板:
<div class="example-component">
<h1>stateTest {{this.mailResult}}</h1>
</div>
我只需要在请求成功后更新我模板中的this.mailResult,一切正常,但模板中的值在请求后不会更新。您知道问题可能隐藏在哪里吗?它不起作用,因为您将组件的更改检测设置为“onPush”,并且mailResult没有用@Input修饰(显然不应该这样做) 因此,要解决此问题,首先需要向类中添加changeDetector:
constructor(private apiService: ApiService, private changeDetector: ChangeDetectorRef) {
this.mailResult = 'notsent'; //updating in template
}
然后使用changeDetector的markForCheck函数让angular知道某些内容已更改,需要更新视图:
this.apiService.testPostRequest().subscribe((res)=>{
console.log("res", res); // working fine loging res
this.mailResult = 'requestsucess'; // not update in template
this.changeDetector.markForCheck();
});
它不起作用,因为您将组件的更改检测设置为“onPush”,而mailResult没有用@Input修饰(显然不应该这样) 因此,要解决此问题,首先需要向类中添加changeDetector:
constructor(private apiService: ApiService, private changeDetector: ChangeDetectorRef) {
this.mailResult = 'notsent'; //updating in template
}
然后使用changeDetector的markForCheck函数让angular知道某些内容已更改,需要更新视图:
this.apiService.testPostRequest().subscribe((res)=>{
console.log("res", res); // working fine loging res
this.mailResult = 'requestsucess'; // not update in template
this.changeDetector.markForCheck();
});
您可以尝试在模板中检测更改吗?您不需要使用{{this.}},只需使用{{mailResult}。尝试更新您的代码,所以当您这样做时。subscribe(res=>this.myNewFunction(res))。然后创建一个新函数myNewFunction(res){this.mailResult='requestsuccess';console.log(mailResult)}。这将更新模板并将日志记录到控制台“requestsuccess”,您不需要在html页面中使用
此
。只需尝试使用{{mailResult}}
请检查可能的重复。您可以尝试检测模板中的更改,您不需要使用{{this.}},只需使用{{mailResult}。尝试更新您的代码,所以当您这样做时。subscribe(res=>this.myNewFunction(res))。然后创建一个新函数myNewFunction(res){this.mailResult='requestsuccess';console.log(mailResult)}。这将更新模板并将日志记录到控制台“requestsuccess”,您不需要在html页面中使用此
。只需尝试使用{{mailResult}}
请检查可能的副本