简体   繁体   中英

Angular 2 passing data to another component

I am new to Angular 2 and am still figuring things out. I have two components:

1) List Component

This lists all the products in a store and does other functions

@Component({
    selector :'home-list',
    providers :[CartService,CartStatus]

})

@View({
    templateUrl :'/app/views/list-product.partial.html'

})

export class HomeList{
    title: string;
    products : ProductInterface[];
    cart;
    private isFetching: boolean = false;

    constructor(
        private _router : Router,
        private _dataService: DataService,
        private _cartService: CartService,
        private _cartStatus: CartStatus
    ){}

    ngOnInit(){
        this.title = 'Featured Products';
        this.getfeaturedproducts();
    }
    getfeaturedproducts(){
        this._dataService.getFeatured().subscribe(
            products => {
                this.products = products;
                this.isFetching = true;
            }
        )
    }

    gotoDetail(slug:string) {
        console.log(slug);
        this._router.navigate(['ProductsDetail', {productslug:slug}]);
        return false;
    }

    getCart(){
        this._cartService.getCartContent().subscribe(
            res => {
                this.cart = res;
                console.log(res.result)
            }
        );
    }

    addtoCart(id:number){
            this._cartService.addToCart(id).subscribe(
                res => console.log(res)
               this._cartStatus.updateCart(id);
             //want to pass the data to CartStatus Component
            )


    }

}

2) CartUpdate Component which shows no of items in cart

@Component({
    selector : 'cart-status'
})

@View({
    template :'{{cart}}'
})

export class CartStatus{

    cart;

    updateCart(id:number){

        this.cart = id;
    }


}

The problem is that I have not been able to pass the id or any value to the CartStatus view. When I console.log the id on updateCart it shows accurate value but does not reflect on the view of the CartStatus.

Am I doing something wrong here??

From your code, what I can figure out is CartStatus is a component so,

 providers :[CartService,CartStatus]

should be,

providers  :  [CartService]
directives :  [cardStatus]

Now, check this official docs for communication between components,
https://angular.io/docs/ts/latest/cookbook/component-communication.html

I am also creating a large scale shopping cart using MEAN stack with Angular 2

As for me adding items to a cart is not so easy for me to implement. User has items(products, qty, total price), User has orderedItems(items, totalQty, totalPrice), User - logged in, all session cart items are cleared and added to user items and so on. I implemented my cart with MongoStore (session with expiration date) so that when you refresh the page, the items are still stored in the cart. MongoStore is a long subject and I can not help you here. There is a tutorial in Utube(angular 1 by MAX from Udemy and that's how I learned it). Honestly, I do not know how to store a "class object" in a LocalStorage. For learning purposes of how to add items to a cart is to use array.

Lets' create a Cart class:

export Class {
    public product: Product;
    public qty: number) {}
}

Create a service: cart.service.ts

import { Injectable } from '@angular/core';
import { Cart } from './cart';
import { Product } from './product';
@Injectable()
export class CartService {
    private carts: Carts[];
    getCart() {
        return this.carts;
    }
    addToCart(product: Product) {
        for(let i=0; i<this.carts.length; i++) {
            if(this.carts[i].product.productId == product.productId) {
                this.carts[i].quantity = this.carts[i].quantity + 1;
                return;
            }
            let cart = new Cart(product, 1);
            this.carts.push(cart;
         }
    }
    getCartTotal(){
        let total = 0;
        for(let i=0; i<carts.length; i++) {
            total = total + this.carts[i].quantity;
        }
        return total;
    }
    emptyCart() {
        this.carts = [];
    }
}

In your cart component:

export class CartStatus implements OnInit {
  carts: Cart[];
  constructor(private: _cartService: CartService) {
  ngOnInit(){
      this.carts = this._cartService.getCart(); //no subsribe() here since is not an http request.
}    

Please don't forget to add CartService to to your boot file. I hope this helps. I can also help you with deleteItem, updateItem, and getTotalCost. Thanks and Happy coding..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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