从服务中删除数据不会从组件中删除

时间:2019-06-19 16:24:39

标签: angular

我有一项服务,用于存储我的应用程序中使用的一些数据,这就是该服务:

@Injectable()
export class StoreService {
    public category: Array<any>;
    public client: Array<any>;

    public fetch(fetch: any): void {
        this.category = fetch.category;
        this.client = fetch.client;
    }

    public insert(array: string, object: any): void {
        return this[array].unshift(object);
    }

    public update(array: string, newObject: any): void {
        let object = this[array].find(obj => obj.id === newObject.id);

        if (object) {
            const index = this[array].indexOf(object);

            this[array][index] = { ...newObject };
            this[array] = [...this[array]];
        }
    }

    public remove(array: string, id: number): void {
        this[array] = this[array].filter(object => object.id !== id);
    }
}

在我的组件中,我这样调用这些函数:

export class CategoryComponent {
    public category: Array<any> = [];

    constructor(
        private _store: StoreService,
    ) {
        this.category = this._store.category;
    }

    public insert() {
        // To simpify the code, let's assume the http request already happened
        // successfully and I received the response
        this._store.insert('category', response.object);
    }

    public update(category: any) {
        // To simpify the code, let's assume the http request already happened
        // successfully and I received the response
        this._store.update('category', response.object);
    }

    public remover(category: any) {
        // To simpify the code, let's assume the http request already happened
        // successfully and I received the response
        this._store.remove('category', category.id);
    }
}

当我添加新类别项目或更新其值时,该视图会自动更新项目,而无需执行其他任何操作。但是,当我想从类别列表中删除一个项目时,它并没有从HTML视图中删除该项目。

如果我在storeService的remove函数中使用console.log,则可以看到从数组中正确删除了该对象。

我发现更新视图的唯一方法是将组件删除功能更改为此:

public remove(category: any) {
    // To simpify the code, let's assume the http request already happened
    // successfully and I received the response
    this._store.remove('category', category.id);
    this.category = this._store.category;
}

如果执行此操作,将从HTML视图中删除类别项目。为什么要删除一项而不添加新项或更改一个值却发生了?

2 个答案:

答案 0 :(得分:0)

在构造函数中,变量this.category成为对this._store.category的引用

当您调用 remove()时,从过滤器返回的新数组将分配给this._store.category,但与此同时this.category仍引用旧数组

我认为解决此问题的最简单方法是从remove()返回一个新数组,然后像

一样使用它
this.category = this._store.remove('category', category.id);

答案 1 :(得分:0)

您考虑的解​​决方案是正确的。我怀疑您的数据有问题,请确保用object插入的insert(array: string, object: any)具有唯一的ID

public remove(category: any) {

    this._store.remove('category', category.id);
    this.category = this._store.category;
}