繁体   English   中英

如何在角度4中创建类型接口的对象?

[英]How to create object of type interface in angular 4?

我正在一家单页购物商店中工作,但遇到了一个小问题。 我一直在尝试定义接口类型的对象,但无法在此对象中保存任何值。

这是我的代码

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

主要问题是这条线

totals:  ICartItem2; 

它在声明时没有显示错误,但是在我将值存储在该对象中然后显示主对象时,在下一行显示未定义。

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

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

我已经完成了对象数组的工作,并且工作正常

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

当我在控制台中显示时(this.broadcast_obj.items); //显示正常。

这是完整的代码

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

}

标头组件代码

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

}

服务代码

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

}

您在填充items的属性this.broadcast_objthis.items 但是,您没有对totals属性进行初始化。 因此它显示为未定义。 如果执行console.log(this.totals)您将获得正确的输出。 我相信您需要添加this.broadcast_obj.totals = this.totals; 之后this.totals = {total_items:this.total_items,total_sum:this.total_sum}

编辑

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

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM