发出后请求后,我无法更新Angular模板,
以下是组件:
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>
和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', {});
}
}
我所需要的只是在请求成功后更新模板中的this.mailResult,一切正常,但是模板中的值在请求后不会更新。有什么想法可以隐藏该问题吗?
答案 0 :(得分:1)
这是行不通的,因为您已将组件的更改检测设置为“ 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();
});