Luc*_*s_R 8 http node.js web typescript angular
在我的angular 2应用程序中,有一个包含一个对象数组的组件,它将所选(单击的)一个传递给它的直接子组件.这确实显示了更详细的数据.我正在使用"SimpleChanges"功能来监视此子组件,如果给定的对象发生更改,则发出另一个http请求以从数据库获取相关注释.
如果我尝试使用npm构建它,我会收到错误,说:
app/displayEntry.component.ts(23,41):错误TS2339:类型'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 ) {
}
}
Run Code Online (Sandbox Code Playgroud)
子组件:
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
}
}
Run Code Online (Sandbox Code Playgroud)
sup*_*ary 11
对于TypeScript而言,接受的解决方案并不理想,因为您正在打败类型系统.
SimpleChanges没有entry属性,所以编译器非常正确.解决方案是将changes对象视为一个数组:
ngOnChanges(changes : SimpleChanges){
if (changes['entry']) {
this.service.getComments(changes['entry'].currentValue.id)
}
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以继续强烈键入ngOnChanges方法.
为了使编译器不会抱怨,只需将参数1的方法定义从SimpleChanges更改为any:
ngOnChanges(changes: any) {
//...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2399 次 |
| 最近记录: |