0

I am currently writing an application that allows a user to add categories to a product. I am pulling every category though that exists from my API and also the categories that are already allocated to that product. I then want to compare the two arrays of objects and if the category is already in the allocated categories for that product I don't want to display it as an option for the product to be allocated to so you cannot add a product to a category that it is already allocated to.

Here is an example of my API data:

Allocated categories for the product:

{id: "3", name: "Vitamins and Minerals ", description: "", created_at: "2016-08-15 09:21:05",…}

All categories on my application:

0:
{id: "1", name: "Detergents and Disinfectants", description: "", created_at: "2016-08-15 09:21:05",…}
1
:
{id: "2", name: "Poultry Equipment", description: "", created_at: "2016-08-15 09:21:05",…}
2
:
{id: "3", name: "Vitamins and Minerals ", description: "", created_at: "2016-08-15 09:21:05",…}
3
:
{id: "4", name: "Gut Health ", description: "", created_at: "2016-08-15 09:21:05",…}
4
:
{id: "5", name: "Rodent, Mite and Fly Control", description: "", created_at: "2016-08-15 09:21:05",…}
5
:
{id: "6", name: "Protective Clothing", description: "", created_at: "2016-08-15 09:21:05",…}

Now, as you can see, the allocated category needs to be removed from my categories to display array so it is not an option for that product. I cannot seem to get it taken out of the array. I have tried this on the view:

<a *ngIf='allocatedCategories.indexOf(category) === -1'>{{category.name}}<i class='glyphicon glyphicon-plus'></i></a>

But this doesn't work and also this on the controller:

alreadyAllocated(category) {
        for(var i = 0; i < this.allocatedCategories; i++) {
            if(this.allocatedCategories[i]['id'] == category.id) {
                return false;
            }
        }
        return true;
    }

Here is my whole component controller if it helps:

import { Component, Input } from "@angular/core";
import { Product } from "../../../../classes/Product";
import { ProductService } from "../../../../services/product.service";
import { Subscription } from "rxjs";
import { ActivatedRoute } from "@angular/router";
import { Location } from '@angular/common';
import { TabsService } from "../../../../services/tabs.service";
import { CategoryService } from "../../../../services/category.service";

@Component({
    selector: 'product-edit',
    templateUrl: '/app/views/catalog/products/directives/product-edit.html',
    moduleId: module.id
})

export class ProductEditComponent {
    public product:Product;
    private categories = {};
    private allocatedCategories = [];
    private searchTerm = '';
    private _subscription: Subscription;
    public id: number;
    public tabs:Array<any> = [
        {title: 'General', content: '', active: true, linked: 'general'},
        {title: 'Images', content: '', active: false, linked: 'images'},
        {title: 'Categories', content: '', active: false, linked: 'categories'},
        {title: 'Manufacturers', content: '', active: false, linked: 'manufacturers'}
    ];
    private selectedTab: Object = this.tabs[0];

        constructor(
        private _productService: ProductService,
        private _categoryService: CategoryService,
        private _activatedRoute: ActivatedRoute,
        private _location: Location,
        private _tabsService: TabsService
    ) {
        this._tabsService.emitter
            .subscribe((tab) => {
                this.tabs.filter((arrayItem) => {
                    if(arrayItem.title === tab.title) {
                        this.selectedTab = arrayItem;
                    }
                });
            }, () => {

            }, () => {

            });

    }

    getProduct() {
        var self = this;
        this._productService.getProduct(this.id)
            .subscribe(
                (product) => {
                    self.product = product[0];
                }
            );
    }

    getCategories(filters) {
        var self = this;
        this._categoryService.getCategories(filters)
            .subscribe((categories) => {
                self.categories = categories;
            });

    }

    getAllocatedCategories() {
        var self = this;
        this._categoryService.getCategories({
            product: self.id
        }).subscribe((categories) => {
            self.allocatedCategories = categories;
        });
    }

    searchCategories() {
        var self = this;
        this.getCategories({
            'search_term' : self.searchTerm
        });
    }

    alreadyAllocated(category) {
        for(var i = 0; i < this.allocatedCategories; i++) {
            if(this.allocatedCategories[i]['id'] == category.id) {
                return false;
            }
        }
        return true;
    }

    back() {
        this._location.back();
    }

    ngOnInit() {
        var self = this;
        this._subscription = this._activatedRoute.params.subscribe(params => {
            self.id = +params['id'];
            this.getProduct();
        });
        this.getCategories({});
        this.getAllocatedCategories();
    }

    ngOnDestroy() {
        this._subscription.unsubscribe();
    }
}

Can anyone see why this is not working?

Thanks

1 Answer 1

1

What about having a method to remove the duplicated categories from the array?

private removeDuplicatedCategories(prodCategories: any[], toBeRemoved: any[]) {
    let i: number = 0;
    while (i < prodCategories.length) {
        for (let toRem of toBeRemoved) {
            if (toRem.id === prodCategories[i].id) {
                prodCategories.splice(i, 1); // remove duplicated
                continue;
            }
        }
        ++i;
    }
}

The method above will modify the original array. Instead, if you want to preserve the original categories array, you can have this method returning another array with the non-duplicated categories:

private removeDuplicatedCategories(prodCategories: any[], toBeRemoved: any[]): any[] {
    let ret: any[] = []; // new array to be returned
    for (let pc of prodCategories) {
        let isDup: boolean = false;
        for (let toRem of toBeRemoved) {
            if (pc.id === toRem.id) {
                isDup = true;
                break;
            }
        }
        if (!isDup) ret.push(pc); // append non-duplicated
    }
    return ret;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.