Swarovski
Swarovski

Reputation: 591

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

Upvotes: 0

Views: 65

Answers (1)

Boris Lobanov
Boris Lobanov

Reputation: 2454

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

Upvotes: 1

Related Questions