Вызывающая переменная Angular 4 из другого компонента не обновляет значение? - PullRequest
0 голосов
/ 27 апреля 2018

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();
    }
  }

Это мой файл фильтра товаров. Я хочу обновить стоимость товаров в другом файле. 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();
  }
}

Я хочу изменить значение продуктов, используя фильтр, согласно выбору пользователя, я получил значения из функции, но когда я пытаюсь обновить его через productFilter, он не работает.

1 Ответ

0 голосов
/ 27 апреля 2018

Создайте новую услугу (введите ng g service <yourServiceName> в свой терминал). В сервисе:

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

Теперь вызовите holdProducts () из компонента, в котором вы хотите сохранить значение, передав products в качестве параметра. В компоненте для извлечения вызовите функцию retrieveProducts () и сохраните ее в переменной.

Вы можете установить флаг или проверить каким-либо образом перед извлечением во 2-м компоненте, что значение заполнено (или, возможно, включить эту логику в retrieveProducts ())

...