首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ngFor创建新元素,但在浏览器刷新之前不会显示新的POSTed数据。

ngFor创建新元素,但在浏览器刷新之前不会显示新的POSTed数据。
EN

Stack Overflow用户
提问于 2018-08-02 15:48:50
回答 1查看 799关注 0票数 0

我对棱角很陌生,并且从我的*ngFor指令中得到了意想不到的结果。

当我单击“add”按钮时,将创建一个新的<li>元素,但在刷新浏览器之前不会显示它的{{ tomato.name }}数据:

添加“Test2”输入和刷新浏览器后的屏幕截图:

添加了'Test2'

刷新后的

component.html

代码语言:javascript
复制
<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

代码语言:javascript
复制
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

代码语言:javascript
复制
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);
  }

}

提前感谢!

EN

回答 1

Stack Overflow用户

发布于 2018-08-02 16:02:00

ChangeDetectorRef导入@angular/core并在this.tomatos.push(tomato)之后手动运行更改检测,如下所示:

代码语言:javascript
复制
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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51657661

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档