我正在构建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>
成功添加数据后,导致列表不更新的原因是什么?
请注意,我已经阅读了所有其他相关问题,但无法解决此问题。
答案 0 :(得分:1)
如@ Farasi78所述,getThings仅被调用一次。因此,我创建了一个handleThingList()函数,该函数在onInit以及每次在列表中插入新项时都会调用
handleThingList()
this.authService.getThings().subscribe(things => {
if (things) {
this.things = things;
this.noThings = false;
}
else {
this.noThings = true;
}
})
我不知道这是否是正确的方法。但这有效!
谢谢大家的友好回答!