首页 > 解决方案 > 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);
  }

}

提前致谢!

标签: angulartypescriptangular6

解决方案


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

希望这会帮助你!


推荐阅读