### File

`modules/basketservice/src/basket.service.ts`

### Description

Service that have logic to work with basket

### Constructor

`constructor(sessionFlow: any, dal: any)`

### Methods

updateProducts
`updateProducts()`
Calls {@link getProducts} with user id if exists, otherwise device id Returns: `void`

getProducts
`getProducts(id: any)`

Get products from database and update on client

Parameters :

- id

  user id or device id

Returns: `void`

addProduct
`addProduct(product: any)`

Add product to database

Parameters :

- product : `Object`

  object of product

Returns: `void`

removeProduct
`removeProduct(item: any)`

Remove product from basket

Parameters :

- item

  product to remove

Returns: `void`

### Properties

basketHistory
`basketHistory: `any` </bcode>`

products
`products: `any` </bcode>`

productsSnapshot
`productsSnapshot: `any[]` </bcode>`

totalPrice
`totalPrice: `number` </bcode>`
Default value: `0`

userId
`userId: `string` </bcode>`

    import { DbAbstractionLayer } from '@nodeart/dal/index';
    import {Injectable} from "@angular/core";
    import {SessionFlow} from "@nodeart/session-flow/index";
    import { Subject } from "rxjs/Subject";

    /**
     * Service that have logic to work with basket
     */
    @Injectable()
    export class BasketService{

      products: Subject<any[]> = new Subject<any[]>();
      productsSnapshot = [];
      totalPrice: number = 0;
      userId: string;
      basketHistory;
      constructor(private sessionFlow: SessionFlow, private dal: DbAbstractionLayer){
        this.products.subscribe(products => {
          this.productsSnapshot = products;
          this.totalPrice = 0;
          for(let i = 0; i < products.length; i++){
            this.totalPrice += +products[i].product.price;
          }
        });
        if(sessionFlow.userId === 'guest'){
          this.getProducts(sessionFlow.deviceId);
          this.basketHistory = this.dal.getBasketHistoryById(this.sessionFlow.deviceId);
        }
        this.dal.getAuth().onAuthStateChanged((data) => {
          if(data == null){
            this.userId = null;
          }
          if(data){
            this.userId = data.uid;
            console.log(this.userId);
            this.getProducts(this.userId);
            if(this.userId != ""){
              this.basketHistory = this.dal.getBasketHistoryById(this.userId);
            }
          }
        });
      }

      /**
       * Calls {@link getProducts} with user id if exists, otherwise device id
       */
      updateProducts(){
        if(this.userId){
          this.getProducts(this.userId);
        }else{
            this.getProducts(this.sessionFlow.deviceId);
        }
      }

      /**
       * Get products from database and update on client
       * @param id user id or device id
       */
      getProducts(id){
        this.dal.getBasketContent(id).on('value', data => {
          if(!data.exists()){
            this.products.next([]);
          }
          if(data.val()){
            let products = Object.keys(data.val()).map((key) => {
              let item = data.val()[key];
              item['idInBasket'] = key;
              return item;
            });
            let ids = products.map(item => {
              return item['id'];
            });
            let queryObj = {
              query: {
                ids: {
                  values: ids
                }
              }
            };
            this.dal.getProductsByIds(queryObj).on('value', data => {
              if(data.val()){
                let result = [];
                for(let i = 0; i < products.length; i++) {
                  for(let j = 0; j < data.val().length; j++){
                    let product = data.val()[j];
                    if(products[i]['id'] === product['_id']){
                      products[i]['product'] = product['_source'];
                      result.push(products[i]);
                    }
                  }
                }
                console.log(result);
                this.products.next(result);
              }
            });
          }
        });
      }

      /**
       * Add product to database
       * @param {Object} product object of product
       */
      addProduct(product){
        if(this.userId){
          this.dal.addProductToBasket(this.userId, product).then(data => {
            this.getProducts(this.userId);
          });
        }else{
          this.dal.addProductToBasket(this.sessionFlow.deviceId, product).then(data => {
            this.getProducts(this.sessionFlow.deviceId);
          });
        }
        // this.products.push(product);
        console.log(product);
        this.basketHistory.push({
          action: "added",
          product: product
        });
      }

      /**
       * Remove product from basket
       * @param item product to remove
       */
      removeProduct(item){
        let idInBasket = item.idInBasket;
        let attributes = null;
        if(item.attributes){
          attributes = item.attributes;
        }
        let product = {
          id: item.id,
          attributes: attributes
        }
        console.log({
          action: "deleted",
          product: product
        });
        if(this.userId){
          this.dal.removeProductFromBasket(this.userId, idInBasket);
        }else{
          this.dal.removeProductFromBasket(this.sessionFlow.deviceId, idInBasket);
        }
        this.basketHistory.push({
          action: "deleted",
          product: product
        });
      };

    }

# results matching ""

# No results matching ""