Search code examples
angularobjectangular2-directives

How to create object of type interface in angular 4?


I am working on a single page shopping store but stuck in a small problem. I have been trying to define an object of type interface but I am unable to save any value in this object.

This is my code

interface ICartItem2 {
    total_items: number;
    total_sum: number;
}

    items: Array<ICartItem> = []; //array of objects working fine
    totals:  ICartItem2; //this is my faulty object of type interface ICartItem2 
    total_items:number=0;
    total_sum:number = 0;
    cart: ICartItem;
    broadcast_obj = {items:[],totals:{}}; //object to store array of objects and single object

The main problem is this line

totals:  ICartItem2; 

It shows no error at declaration, but at the following line when I am storing values in this object and then showing main object it is showing undefined.

this.totals = {total_items:this.total_items,total_sum:this.total_sum}

console.log(this.broadcast_obj.totals); // showing undefined

I have done same with array of objects and it is working fine

this.cart = {id:id, name: itemText, price: amount,quantity:1};
this.items.push(this.cart);

and when I show in console(this.broadcast_obj.items); //it shows fine.

Here is the full code

import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';
interface ICartItem {
    id: number;
    name: string;
    price: number;
    quantity: number;
}
interface ICartItem2 {
    total_items: number;
    total_sum: number;
}
@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})

export class HomeComponent implements OnInit {

    items: Array<ICartItem> = []; 
    totals:  ICartItem2;
    total_items:number=0;
    total_sum:number = 0;
    cart: ICartItem;
    broadcast_obj = {items:[],totals:{}};
    duplicate:ICartItem ;
    constructor(private _data: DataService) {  }

    ngOnInit() {
        //this.items_count = this.cart.length;
        this._data.cast.subscribe(res => this.broadcast_obj = res);
        this._data.changeCart(this.broadcast_obj);
    }

    additem(id,itemText,amount){
        if(this.items.length==0){//no item in the array
            this.cart = {id:id, name: itemText, price: amount,quantity:1};
            this.items.push(this.cart);
        }
        else{
            this.duplicate = this.items.find(x => x.id == id);//check if item already exists in the cart
            if (this.duplicate === null || this.duplicate === undefined) { //item object not found in the array
                this.cart = {id:id, name: itemText, price: amount,quantity:1};
                this.items.push(this.cart);
            }
            else if(this.duplicate.id===id){
                this.duplicate.quantity++;
            }
        }

        this.broadcast_obj.items = this.items;
        this.total_items++;
        this.total_sum += amount;
        this.totals = {total_items:this.total_items,total_sum:this.total_sum}

        console.log(this.broadcast_obj.totals);
        this._data.changeCart(this.broadcast_obj);
    }

}

Code of header component

import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';

interface ICartItem {
    id: number;
    name: string;
    price: number;
    quantity: number;
}
interface ICartItem2 {
    total_items: number;
    total_sum: number;
}


@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.scss']
})
export class HeaderComponent implements OnInit {
    cart: Array<ICartItem> = [];
    totals:  ICartItem2;
    total_items:number = 0;
    total_sum:number = 0;
    showHide: false; 
    constructor(private _data: DataService) {

    }

    ngOnInit() {
        this._data.cast.subscribe(res =>{
            this.cart = res.items;
            this.total_items = res.totals.total_items;
            //this.total_sum =   res.totals.total_sum;
        });
    }

    addClass(toggle) {
        console.log(this.total_items);
        this.showHide = toggle;
    }

}

service code

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

@Injectable()
export class DataService {

    private cartobj = new BehaviorSubject<any>({});
    cast = this.cartobj.asObservable();

    constructor() { }

    changeCart(item_param) {
        this.cartobj.next(item_param);
    }

}

Solution

  • You are populating the items property of this.broadcast_obj with this.items. But you are leaving totals property uninitialized. Thus it is showing as undefined. If you do console.log(this.totals) you will get the correct output. I believe you need to add this.broadcast_obj.totals = this.totals; after this.totals = {total_items:this.total_items,total_sum:this.total_sum}

    EDIT

    import { Component, OnInit } from '@angular/core';
    import { DataService } from '../data.service';
    interface ICartItem {
        id: number;
        name: string;
        price: number;
        quantity: number;
    }
    interface ICartItem2 {
        total_items: number;
        total_sum: number;
    }
    @Component({
      selector: 'app-home',
      templateUrl: './home.component.html',
      styleUrls: ['./home.component.scss']
    })
    
    export class HomeComponent implements OnInit {
    
        items: Array<ICartItem> = []; 
        totals:  ICartItem2;
        total_items:number=0;
        total_sum:number = 0;
        cart: ICartItem;
        broadcast_obj = {items:[],totals:{}};
        duplicate:ICartItem ;
        constructor(private _data: DataService) {  }
    
        ngOnInit() {
            //this.items_count = this.cart.length;
            this._data.cast.subscribe(res => this.broadcast_obj = res);
            this._data.changeCart(this.broadcast_obj);
        }
    
        additem(id,itemText,amount){
            if(this.items.length==0){//no item in the array
                this.cart = {id:id, name: itemText, price: amount,quantity:1};
                this.items.push(this.cart);
            }
            else{
                this.duplicate = this.items.find(x => x.id == id);//check if item already exists in the cart
                if (this.duplicate === null || this.duplicate === undefined) { //item object not found in the array
                    this.cart = {id:id, name: itemText, price: amount,quantity:1};
                    this.items.push(this.cart);
                }
                else if(this.duplicate.id===id){
                    this.duplicate.quantity++;
                }
            }
    
            this.broadcast_obj.items = this.items;
            this.total_items++;
            this.total_sum += amount;
            this.totals = {total_items:this.total_items,total_sum:this.total_sum}
            console.log(this.totals)            //Should give you valid log
            this.broadcast_obj.totals = this.totals; //Added as per my answer
            console.log(this.broadcast_obj.totals);
            this._data.changeCart(this.broadcast_obj);
        }
    
    }