首页 > 解决方案 > http请求后Angular模板未更新

问题描述

发出后请求后,我无法更新我的 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,一切正常,但模板中的值在请求后不会更新。任何可能隐藏问题的想法?

标签: javascriptangular

解决方案


它不起作用,因为您将组件的更改检测设置为 '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();
  });

推荐阅读