2016-09-29 9 views
6

私の角2のアプリケーションでは、選択された(クリックされた)ものを直接子コンポーネントに渡すオブジェクトの配列を含むコンポーネントがあります。これにより、より詳細なデータが表示されます。私は "SimpleChanges"機能を使用して、この子コンポーネントで、与えられたオブジェクトがデータベースから関連するコメントを取得するために別のhttp要求を行うように変更された場合にそれを見ています。角2のSimpleChangesオブジェクトは、最初にnpmの開始時にエラーをスローします

私はNPMでそれを構築しようとすると、私は言って、エラーを取得:

アプリ/ displayEntry.component.ts(23,41):エラーTS2339:プロパティ「エントリは」タイプに存在しません。 '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 
} 
} 

答えて

2

コンパイラはちょうどanySimpleChangesからパラメータ1のためのあなたの方法の定義を変更文句ないようにするには:

ngOnChanges(changes: any) { 

//... 
8

許容される解決策は、タイプに対して最適以下ですあなたがタイプシステムを破っているようにスクリプト。

SimpleChangesは、entryというプロパティを持っていないので、コンパイラはかなり正しく失敗します。解決策は、配列としてchangesオブジェクトを扱うことです:

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

次にあなたが強くngOnChanges方法を入力し続けることができます。

+1

さらに、現在の変更が「入力」フィールドに変更を加えているかどうかを確認してください。たとえば、 'if( 'エントリ'が変更されたもの)'とします。 – PhoneixS

+0

この回答は受け入れる必要があります。 –

+0

@PhoneixS - 良い点、よく作られています。私は答えを調整しました。 – superluminary

関連する問題