Search code examples
rxjsbehaviorsubject

Pass nested object on intanciate class


When I try to pass nested object on the new Class(), it returns empty class.

I think it's because I pass wrong arguments.

class myClass {
    public selected: {
        category: {
            code: string
        }
    } = {}
}

const initialState = {
    selected: {
        category: {
            code: ''
        }
    }
}

private bs: BehaviorSubject<any> = new BehaviorSubject(initialState)

That's work good, I get myClass with values.

But when I want to pass values after :

setCategory (myCategory) {
    let value = this.bs.getValue();
    let newValue = Object.assign({}, value, {
                    selected: {
                        category:{
                            code: myCategory
                        }
                    }
                });
     new myClass(newValue) // return { view: {}, selected: { category: { code: '' } } }
}

I get { view: {}, selected: { category: { code: '' } } }

UPDATE

Live code : https://stackblitz.com/edit/angular-bjlhus?file=app%2Fapp.component.ts


Solution

  • You need to add the constructor to your class to assign the input parameter to the selected property:

    constructor(state) {
        this.selected = state.selected;
    }
    

    Here's the stackblitz with the fix: https://stackblitz.com/edit/angular-hokh2a