2017-07-29 23 views
0

として、特定のクラスのインスタンスを考慮する:角度私は角度4に次のサービスを持っているオブジェクト

import { Injectable, EventEmitter } from '@angular/core'; 
import {Recipe} from './recipe' 
import {Ingredient} from '../shared/ingredient' 
@Injectable() 
export class RecipeService { 

    private recipes:Recipe[]=[new Recipe("Dummy","Dummy","http://media.wiley.com/product_data/coverImage300/2X/04707687/047076872X.jpg",[new Ingredient("French Food",5),new Ingredient("Dummy Book",1)]), 
        new Recipe("jahangiri","a perfect vice president","http://biographyha.com/wp-content/uploads/2014/12/Eshaq-Jahangiri-biographya-com-2.jpg",[new Ingredient("French Food",5),new Ingredient("Dummy Book",1)]) ] 

    //do some functionalities 

    getRecipe(id:number) 
    { 
    return this.recipes[id]; 
    } 
    editRecipe(oldRecipe:Recipe,newRecipe:Recipe) 
    { 
    this.recipes[this.recipes.indexOf(oldRecipe)]=newRecipe as Recipe; 
    console.log(newRecipe as Recipe) 
    } 

    //do other functionalities 
} 

レシピ成分たアプリで使用されるクラスです。 私はそのことを期待しますeditRecipe関数は、意図したインデックスに置換されます。置換後挿入されたアイテムのgetRecipeは失敗します。 挿入されたアイテムはオブジェクトと見なされるため、レシピの代わりに、私は明示的なキャストを行っていますが、見つけられません。 私は何ができますか? ありがとうございます。

+0

存在しないオブジェクトが見つからない場合は、オブジェクトが最初に存在するかどうかを確認してオブジェクトを取得する必要があります。 –

+0

目的のアイテムが存在していますが、確認するために配列を記録しましたが、** Recipe **の代わりに** Object **として保存されています。 –

+0

オブジェクトの種類は? –

答えて

0

はFormGroupのフィールドがあったことを確認していました私のクラスの同じフィールドの成分。私はそこで間違いを犯しました。これは引数がと推論できない理由です。レシピ ありがとう皆さんありがとうございます。

0

as Recipeは、プロトタイプを設定しません。JavaScriptに変換されたときに削除される単なる注釈注釈です。これは型チェックのためにのみ存在します。

(あなたが必要なすべてのプロパティを作成したい場合は型自体)あなたが代わりにこのようなレシピコンストラクタで部分オブジェクトを使用することができます。

constructor(partial: Partial<Recipe>) { 
    if (partial) { 
    this.name = partial.name 
    this.url = partial.url 
    } 
} 

してから編集するレシピ使用中

をそれが原因フォームhandling.Iを扱う間違いに実際にいた
this.recipes[this.recipes.indexOf(oldRecipe)] = new Recipe(newRecipe); 

Live plunker example

関連する問題