我是Angular的新手,我的*ngFor
指令得到了意外的结果。
当我单击“添加”按钮时,创建了一个新的<li>
元素,但是直到刷新浏览器后,才显示{{ tomato.name }}
数据:
我添加“ Test2”输入时以及刷新浏览器后的屏幕截图:
添加了“ Test2”
刷新后
component.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>
component.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;
}
service.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);
}
}
谢谢!
答案 0 :(得分:1)
从@angular/core
导入ChangeDetectorRef
,并在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));
}
希望这对您有帮助!
答案 1 :(得分:0)
使用tomato?.name
会起作用,因为此属性在尝试绑定的时间没有值