javascript - 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,一切正常,但模板中的值在请求后不会更新。任何可能隐藏问题的想法?
解决方案
它不起作用,因为您将组件的更改检测设置为 '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();
});
推荐阅读
- r - 如何将基于列的大型数据框转换为 R 中的数据框列表
- pandas - pandas 安装失败,出现来自 setup.py 的错误“错误:没有为 pandas 找到匹配的发行版”
- hibernate - Spring boot 2 多数据源问题 - IllegalArgumentException:名称不能为空
- c++ - 当字符串是某个单词时给出输出?
- c++ - 无法在 dll ${pathToDir}\demoGame.exe 中找到程序入口点 _ZdlPvj
- google-api - 在博客 API 中,quotaUser 参数有什么作用?
- blazor - 是否有与 WinForm 的 PropertyGrid 等效的 Blazor?
- spring-boot - 如何在 Apache Cassandra 中指定某个协调器节点列表?
- python - 在视图内查询时测试数据库为空
- mysql - 无法连接到 WSO2 上的 mysql 数据库