Search code examples
angularlodash

Angular 4 calling variable from another component not update the value?


productFilterComponent.ts

import {Component, OnInit} from '@angular/core';
import {ProductFilterService} from '../../services/product_filter.service';
import {ProductService} from "../../services/products.service";
import {NormalproductfilterComponent} from "./normalproductfilter/normalproductfilter.component";
import * as _ from "lodash";

@Component({
  selector: 'app-productfilter',
  templateUrl: './productfilter.component.html',
  styleUrls: ['./productfilter.component.css'],
  directives: [NormalproductfilterComponent]
})
export class ProductfilterComponent implements OnInit {

  brands: any;
  products: any;
  filter_products: any;

  filtered_result = [];
  selected_brands = [];
  Data: any = [];

  color: any[] = ["red", "blue", "green", "orange", "grey", "yellow", "gold"];

  constructor(private _products: ProductService, private _productBrands: ProductFilterService, private normalProduct: NormalproductfilterComponent) {
  }

  getAllBrands() {
    this._productBrands
      .getAllBrands()
      .subscribe(brands => {
        this.brands = brands.Data;

        this.brands.forEach(singleRecord => {
          if (singleRecord.parent == 0) {
            this.Data[singleRecord.name] = singleRecord.id;
          }
        })
      })
  }

  getAllProducts() {
    this._products
      .getAllProducts()
      .subscribe(products => {
        this.products = products.Data;
        console.log(this.products);
      });
  }


  // Getting Selected Games and Count
  getSelected(val, event) {
    var index = this.selected_brands.indexOf(val);
    if (index === -1) {
      this.selected_brands.push(val);
    } else {
      this.selected_brands.splice(index, 1);
    }
    console.log(this.selected_brands);
    for (let temp of this.products) {
      if (this.selected_brands != '' || temp != 'undefined') {
        for (let temp2 of this.selected_brands) {
          this.filter_products = _.filter(temp.categories, {'id': temp2});
          if (this.filter_products != '') {

            var indexofFilterProducts = this.filtered_result.indexOf(temp);
            if (indexofFilterProducts === -1) {
              this.filtered_result.push(temp);
            } else {
              this.filtered_result.splice(indexofFilterProducts, 1);
            }
          }
        }
      }
      else {
        this.filtered_result = this.products;
      }
    }

    this.normalProduct.products = this.filtered_result;
  }


  ngOnInit() {
    this.getAllBrands();
    this.getAllProducts();
    }
  }

This is my product filter file i want to update the value of products on another file that is normalProductFilter.ts

import {Component, Injectable, OnInit, Output, EventEmitter} from '@angular/core';
import {ProductfilterComponent} from '../productfilter.component';
import {ProductService} from "../../../services/products.service";

@Component({
  selector: 'app-normalproductfilter',
  templateUrl: './normalproductfilter.component.html',
  styleUrls: ['./normalproductfilter.component.css']
})

@Injectable()
export class NormalproductfilterComponent implements OnInit {
  @Output() data: EventEmitter<any> = new EventEmitter();
  products: any;
  data:any;
  normal_products_image: any[] = ["prdct1", "prdct2", "prdct3", "prdct4", "prdct5", "prdct6", "prdct7", "prdct8", "prdct1", "prdct2", "prdct3", "prdct4",];

  constructor(private _normalProducts: ProductService) {
  }

  getAllProducts() {
    this._normalProducts
      .getAllProducts()
      .subscribe(products => {
        this.products = products.Data;
        console.log(this.products);
      });
  }
  ngOnInit() {
    this.getAllProducts();
  }
}

I want to change the value of products using filter as per user selection i got values from function but when I am trying to update it through productFilter then its not working.


Solution

  • Create a new service (type ng g service <yourServiceName> into your terminal). In the service:

    products:any;
    holdProducts(pProducts: any){
     this.products=pProducts;
    }
    retrieveProducts(){
     return this.products;
    }
    

    Now call holdProducts() from the component where you want to store the value, passing products as a parameter. In the component to retrieve, call the retrieveProducts() function and store it in the variable.

    You could set a flag or check somehow before retrieving, in the 2nd component, that the value has been populated (or maybe incorporate that logic into retrieveProducts())