Reputation: 478
I am can't get my Angular template to update after i sent out a postrequest,
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
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. Any Ideas where the Issue might be hidden?
Upvotes: 1
Views: 2739
Reputation: 3228
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).
So, to fix this, you first need to add a changeDetector to your class:
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:
this.apiService.testPostRequest().subscribe((res)=>{
console.log("res", res); // working fine loging res
this.mailResult = 'requestsucess'; // not update in template
this.changeDetector.markForCheck();
});
Upvotes: 3