angular - ngFor 创建新元素,但在浏览器刷新之前不显示新发布的数据
问题描述
我是 Angular 的新手,并且从我的*ngFor
指令中得到了意想不到的结果。
当我单击“添加”按钮时<li>
,会创建一个新元素,但{{ tomato.name }}
在我刷新浏览器之前不会显示它的数据:
我添加“Test2”输入时以及刷新浏览器后的屏幕截图:
添加了“测试2”
刷新后
组件.html
<div>
<label>Tomato name:
<input #tomatoName />
</label>
<button (click)="add(tomatoName.value); tomatoName.value='';">
add
</button>
</div>
<ul>
<li *ngFor="let tomato of tomatos">
<p>{{ tomato.name }}</p>
</li>
</ul>
组件.ts
import { Component, OnInit } from '@angular/core';
import { TomatoService } from '../services/tomato.service';
@Component({
selector: 'app-tomatos',
templateUrl: './tomatos.component.html',
styleUrls: ['./tomatos.component.css']
})
export class TomatosComponent implements OnInit {
tomatos: Tomato[];
constructor(private tomatoService: TomatoService) { }
ngOnInit() {
this.getTomatos();
}
getTomatos(): void {
this.tomatoService.getTomatos()
.subscribe(tomatos => this.tomatos = tomatos)
}
add(name:string): void {
if (!name) { return; }
this.tomatoService.addTomato({name} as Tomato)
.subscribe(tomato => this.tomatos.push(tomato));
}
}
export interface Tomato {
id: number;
name: string;
originPostCode: string;
tastes: string;
}
服务.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Tomato } from '../tomatos/tomatos.component';
import { Observable, of } from '../../../node_modules/rxjs';
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
@Injectable({
providedIn: 'root'
})
export class TomatoService {
private tomatosUrl = 'https://path/tomy/api'
constructor(private http: HttpClient) { }
getTomatos(): Observable<Tomato[]> {
return this.http.get<Tomato[]>(this.tomatosUrl);
}
addTomato (tomato: Tomato): Observable<Tomato> {
return this.http.post<Tomato>(this.tomatosUrl, tomato);
}
}
提前致谢!
解决方案
ChangeDetectorRef
从以下位置导入@angular/core
并手动运行更改检测this.tomatos.push(tomato)
:
constructor(private tomatoService: TomatoService, private ref: ChangeDetectorRef) { }
ngOnInit() {
this.getTomatos();
}
getTomatos(): void {
this.tomatoService.getTomatos()
.subscribe(tomatos => {
this.tomatos = tomatos;
this.ref.detectChanges();
})
}
add(name:string): void {
if (!name) { return; }
this.tomatoService.addTomato({name} as Tomato)
.subscribe(tomato => this.tomatos.push(tomato));
}
希望这会帮助你!
推荐阅读
- opencv - 是否有任何 opencv android 函数可用于在没有 for 循环的情况下替换像素值?
- xamarin - AppCenter 崩溃和 Firebase Crashlytics - 两者都不起作用 - Xamarin.Forms iOS
- azure - ARM 模板部署返回一个我不期望的值
- powershell - 如何通过 Powershell 找到身份验证域控制器
- kotlin - Kotlin data class with spring jpa
- error-handling - 如何捕获 rust 中的所有错误?
- python - AttributeError:'datetime.date'对象没有属性'tzinfo'Datetime Django
- python - 输出中的错误消息不会在 Visual Studio Code 中关闭
- docker - “docker ps”不显示 Kubernetes 控制的容器的 PORT 详细信息
- hadoop - 如何在同一个配置单元表中使用派生列?