Angular 6 ngFor列表在新插入后不会自动更新

Angular 6 ngFor list does not update automatically after new insertion

我正在构建一个 MEAN 应用程序,但我遇到了 *ngFor 创建新项目后列表未更新的问题。如果我手动刷新列表更新,我知道该项目已成功创建,但它不会自动更新。

my.service.ts

import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { myThings } from '../things';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/Rx';
import { tokenNotExpired } from 'angular2-jwt';

export class AuthService {
constructor(private http:Http, private hTTp:HttpClient) { }
getThings():Observable<myThings[]>{
  const token = localStorage.getItem('id_token');
  let headers = new HttpHeaders();
  headers = headers.append('Authorization', token);
  headers = headers.append('Content-Type', 'application/json');
  return this.hTTp.get<myThings[]>('http://localhost:3000/things/get', { headers: headers });
}
}

things.ts

export interface myThings {
    _id:String,
    user:String,
    name:String,
    devicetype:String,
    state: Boolean,
    analog:Number,
    timestamp:String
}

things.components.ts

import { Component, OnInit, ViewChild } from '@angular/core';
import { AuthService } from '../../services/auth.service';
import { ValidateService } from '../../services/validate.service';
import { Http, Headers } from '@angular/http';
import { Observable } from 'rxjs';
@Component({
  selector: 'app-things',
  templateUrl: './things.component.html',
  styleUrls: ['./things.component.css']
})
export class ThingsComponent implements OnInit {
  things = [];
  noThings: Boolean;

  constructor(private authService:AuthService, private validateService:ValidateService, private http:Http) {
  }

  ngOnInit() {
    this.authService.getThings().subscribe(things => {
      if (things) {
        this.things = things;
        this.noThings = false;
      }
      else {
        this.noThings = true;
      }
    })
  }
}

things.component.html

<div *ngIf="!noThings">
  <a href="" data-toggle="modal" data-target="#createThing">Create thing</a>
  <ul *ngFor="let thing of things">
    <li>Thing: {{thing.name}} Type: {{thing.devicetype}}</li>
  </ul>
</div>

添加数据成功后列表没有更新的原因是什么?

请注意,我已阅读所有其他相关问题,但无法解决此问题。

如@Farasi78 所述,getThings 仅被调用一次。因此,我创建了一个函数 handleThingList(),它在 onInit 以及每次在列表中插入新项目时调用

handleThingList()

this.authService.getThings().subscribe(things => {
      if (things) {
        this.things = things;
        this.noThings = false;
      }
      else {
        this.noThings = true;
      }
    })

我不知道这是不是正确的方法。但它有效!

谢谢大家的热心回答!