2016-01-12 12 views
13

Dire che ho classi Task e TaskGroupCome utilizzare Immesable JS con classi ES6 digitate?

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

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

Poi nel mio angolare 2 servizio creerò un immutabile Elenco dei TaskGroups

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

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

In questo modo solo taskGroups List è immutabile. Qualunque cosa ci sia dentro non lo è. Anche se faccio Immutable.fromJS(...) anziché Immutable.List<Board>(...), gli oggetti nidificati sono semplici oggetti Javascript.

Immutabile JS non suppone di ereditarietà di classe (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 

Così come creare oggetti di classe immutabili?

+1

Si potrebbe voler dare un'occhiata a questo [collegamento] (http://blog.scottlogic.com/2016/01/05/angular2-with-immutablejs.html);) – Kutyel

+0

@Kutyel il wrapper è un bel concetto. Forse dovresti scriverlo come risposta e link all'articolo. –

+0

fatto, grazie per il tuo suggerimento^_^ – Kutyel

risposta

9

Si può fare in questo modo:

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!"}); 

Non perfetto, ma di lavoro.

Proviene da questa grande post del blog: https://blog.angular-university.io/angular-2-application-architecture-building-flux-like-apps-using-redux-and-immutable-js-js/

+2

Non è il tipo che controlla gli argomenti del costruttore. Passa la stringa per id e funziona! –

2

Si può fare un involucro con Immutabile, come indicato in this tutorial:

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); 
    } 
} 

Spero che questo vi aiuterà! ;)

Problemi correlati