[英]Angular Template not updating after http request
I am can't get my Angular template to update after i sent out a postrequest, 我发出后期要求后,无法更新Angular模板,
Here's the component: 这是组件:
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
});
}
}
and that's the template: 那是模板:
<div class="example-component">
<h1>stateTest {{this.mailResult}}</h1>
</div>
and the apiService 和apiService
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { of } from 'rxjs';
@Injectable()
export class ApiService {
constructor(private http: HttpClient) {}
testPostRequest () {
return this.http.post('http://localhost:1337/email', {});
}
}
All I need is to update this.mailResult in my Template after the request was successful, all is working fine, but the value in the template just won't update after the request. 我只需要在请求成功后更新模板中的this.mailResult,一切就可以正常工作,但是模板中的值仅在请求后不会更新。 Any Ideas where the Issue might be hidden?
有什么想法可以隐藏问题吗?
It's not working because you have your component's change detection set to 'onPush' and mailResult is not decorated with @Input (which it obviously shouldn't). 它不起作用,因为您已将组件的更改检测设置为“ onPush”,并且mailResult未使用@Input装饰(显然不应使用)。
So, to fix this, you first need to add a changeDetector to your class: 因此,要解决此问题,您首先需要在类中添加一个changeDetector:
constructor(private apiService: ApiService, private changeDetector: ChangeDetectorRef) {
this.mailResult = 'notsent'; //updating in template
}
And then you use that changeDetector's markForCheck function to let angular know that something has changed and it needs to update the view: 然后,您可以使用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();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.