简体   繁体   中英

Angular Template not updating after http request

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?

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();
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM