Angular 2 SimpleChanges Object在第一个npm开始时抛出错误

在我的angular2应用程序中有一个组件,其中包含一个对象数组,将所选(单击)的对象传递给它的直接子组件。 这会显示更详细的数据。 我正在使用“SimpleChanges”function来观察这个子组件,如果给定的对象改变成另一个http请求来从数据库中获取相关的注释。

如果我尝试用npm构build它,我会得到一个错误,并说:

app / displayEntry.component.ts(23,41):错误TS2339:types'SimpleChanges'上不存在属性'entry'

如果我只是评论这部分,启动npm,并最终把它放在那里,并保存它,没有问题了(没有错误,它的工作原理)。 我的问题是,是否有办法解决这个问题,这会导致什么麻烦,以后我不能预见,还是应该忽略它? 谢谢你的帮助

父组件:

import { Component, OnInit } from '@angular/core'; import { entry } from './Objekte/entry'; import { entryService } from './entry.service' @Component({ templateUrl: 'app/Html_Templates/displayLastEntrys.template.html' }) export class displayLastEntrys implements OnInit{ public entrys : entry[]; private entryChoosen: boolean; private ChoosenEntry : entry; constructor ( private entryservice : entryService){ this.entryChoosen = false; } ngOnInit() : void { this.getData(); } getData() { this.entryservice.getFirstEntrys().then(entrys => this.entrys = entrys); } entryClicked(ent: entry){ this.entryChoosen = true; this.ChoosenEntry = ent; } leaveEntry () { this.entryChoosen = false; } voted( upordown : boolean ) { } } 

子组件:

 import { Component, Input, Injectable, OnChanges , SimpleChanges, Output, EventEmitter} from '@angular/core'; import { entry} from './Objekte/entry'; import { entryService } from './entry.service'; import { comment } from './Objekte/comments'; @Component({ selector: 'display-entry', templateUrl: 'app/Html_Templates/displayEntry.template.html' }) export class displayComponent implements OnChanges{ @Input() public entry : entry; public comments : comment[]; private changecounter : number; constructor(private service : entryService) { this.changecounter = 0; } ngOnChanges(changes : SimpleChanges){ this.service.getComments(changes.entry.currentValue.id) .then(com => this.comments = com ) .catch(); this.entry.viewed++; // To implement :: change database } votedUp () : void { this.entry.votes ++; // To implement :: change database } votedDown () : void { this.entry.votes --; // To implement :: change database } } 

为了让编译器不抱怨,只需将参数1的方法定义从SimpleChanges更改为any

 ngOnChanges(changes: any) { //... 

对于TypeScript来说,接受的解决scheme并不理想,因为你正在击败types系统。

SimpleChanges没有entry属性,所以编译器很合适。 解决方法是将changes对象作为数组处理:

 ngOnChanges(changes : SimpleChanges){ if (changes['entry']) { this.service.getComments(changes['entry'].currentValue.id) } } 

然后你可以继续强制键入ngOnChanges方法。