Updating an object in the ngrx/store

前端 未结 4 1660
無奈伤痛
無奈伤痛 2021-01-04 21:52

I\'m using @ngrx/store for an Angular 2 app.

My store holds a list of say, Book objects. I want to update a field in one of those objects. I also happ

4条回答
  •  时光取名叫无心
    2021-01-04 22:42

    One way to accomplish this is a utility/helper method to make a new book from. You could give it an existing book and the subset of properties you want to add to a new book (using Partial in typeScript if you want type safety).

    createNewBook(oldBook: Book, newProps: Partial): Book {
        const newBook = new Book(); 
        for(const prop in oldBook) {
            if(newProps[prop]) {
                newBook[prop]=newProps[prop];
            } else {
                newBook[prop]=oldBook[prop];
            }
        }
        return newBook 
    }
    

    You could call it via newBook = createNewBook(new Book(), {title: 'first foo, then bar'}); and use this newBook to update your store.

提交回复
热议问题