gpt4 book ai didi

node.js - Angular 2 SimpleChanges 对象在第一次 npm 启动时抛出错误

转载 作者:太空狗 更新时间:2023-10-29 17:12:35 26 4
gpt4 key购买 nike

在我的 Angular 2 应用程序中,有一个组件包含一组对象,该对象将选择(单击)的对象传递给它的直接子组件。这确实显示了更详细的数据。如果给定的对象发生更改以发出另一个 http 请求以从数据库中获取相关评论,我正在使用“SimpleChanges”功能在此子组件中进行观察。

如果我尝试使用 npm 构建它,我会收到错误消息:

app/displayEntry.component.ts(23,41): error TS2339: Property 'entry' does not exist on type 'SimpleChanges'

如果我只是将这部分注释掉,启动 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
}
}

最佳答案

公认的解决方案对于 TypeScript 来说不是最优的,因为您正在打败类型系统。

SimpleChanges 没有 entry 属性,因此编译器很正常地拒绝了。解决方案是将 changes 对象视为一个数组:

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

然后就可以继续强类型化ngOnChanges方法了。

关于node.js - Angular 2 SimpleChanges 对象在第一次 npm 启动时抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39763708/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com