2016-01-12 1 views
13

はその後、私の角度2サービスでは、私はTaskGroups型付けされたES6クラスで不変のJSを使用するには?

@Injectable() 
class TaskService { 
    taskGroups:Immutable.List<TaskGroup>; 

    constructor() { 
     this.taskGroups = Immutable.List<TaskGroup>([new TaskGroup("Coding tasks")]); 
    } 
} 

この方法でのみtaskGroups一覧は不変であるの不変のリストを作成します。私は、クラスTask

class Task{ 
    constructor(public text:string){} 
} 

class TaskGroup { 
    constructor(public title:string = "new task group", public tasks:Task[] = []){} 
} 

TaskGroupを持っていると言います。その中にあるものは何でもありません。 Immutable.List<Board>(...)の代わりにImmutable.fromJS(...)を実行しても、ネストされたオブジェクトは普通のJavascriptオブジェクトです。

不変JSはどのように不変クラスのオブジェクトを作成するので、クラスの継承(Inheriting from Immutable object with ES6 #562

//can't do this! 
class TaskGroup extends Immutable.Map<string, any>{ 
    constructor(public title:string = "new task group", public tasks:Task[]){} 
} 
//it complained about the class not having methods like set, delete etc 

を想定していないのですか?

+1

この[link](http://blog.scottlogic.com/2016/01/05/angular2-with-immutablejs.html);)を参照してください。 – Kutyel

+0

@Kutyelはラッパーです素晴らしいコンセプト。おそらくあなたはそれを答えとして書いて、記事にリンクしてください。 –

+0

完了、おかげさまで^ _^ – Kutyel

答えて

9

あなたは次のように行うことができます。

const TodoRecord = Immutable.Record({ 
    id: 0, 
    description: "", 
    completed: false 
}); 

class Todo extends TodoRecord { 
    id:number; 
    description:string; 
    completed: boolean; 

    constructor(props) { 
     super(props); 
    } 
} 

let todo:Todo = new Todo({id: 1, description: "I'm Type Safe!"}); 

完璧しかし働いていません。

それは、この偉大なブログ記事から来ている: https://blog.angular-university.io/angular-2-application-architecture-building-flux-like-apps-using-redux-and-immutable-js-js/

+2

コンストラクタの引数をタイプチェックしていません。 idの文字列を渡すと動作します! –

2

thisチュートリアルで述べたようにあなたは、不変でラッパーを作ることができます。これは役立つ

import { List, Map } from 'immutable'; 

export class TodoItem { 
    _data: Map<string, any>; 

    get text() { 
    return <string> this._data.get('text'); 
    } 

    setText(value: string) { 
    return new TodoItem(this._data.set('text', value)); 
    } 

    get completed() { 
    return <boolean> this._data.get('completed'); 
    } 

    setCompleted(value: boolean) { 
    return new TodoItem(this._data.set('completed', value)); 
    } 

    constructor(data: any = undefined) { 
    data = data || { text: '', completed: false, uuid: uuid.v4() }; 
    this._data = Map<string, any>(data); 
    } 
} 

願っています! ;)

関連する問題