如何将Object从服务传递到组件

时间:2016-10-31 10:43:03

标签: angular typescript service

对于我的网站,我想要一个可以装满物品的购物车。此时我正在尝试使用包含对象形式的购物车cart的服务来处理此问题,该服务具有可向其添加项目的功能,并且还将整个购物车作为承诺返回。目前我只能将商品添加到购物车,但是当我尝试从getCart()调用cart.component.ts时,它似乎会返回一个完全空的数组,而不像我认为的那样存储。我是不是以不正确的方式来做这件事?

cart.service.ts

import {Injectable, EventEmitter} from '@angular/core';
import {Item} from '../../models/item.model';


@Injectable()
export class CartService{
  public cart:Item[] = [];

  constructor(){
  }

  updateCart(){ //just prints the cart size
    console.log('cart size: ' + this.cart.length);
  }
  addItem(item:Item){ //adds an item
    this.cart.push(item);
    this.updateCart();
  }
  checkout(){ //wipes cart
    console.log('cart wiped');
    this.cart = [];
    this.updateCart();
  }


  getCart(): Promise<Item[]>{ //returns the cart
    console.log('getting cart');
    this.updateCart();
    return  Promise.resolve(this.cart);
  }
}
cart.component.ts

    import {Component, OnInit} from '@angular/core';
    import { CartService } from './cart.service';
    import {Item} from '../../models/item.model';


    @Component({
      moduleId: module.id,
      selector: 'sd-cart',
      templateUrl: 'cart.component.html',
      styleUrls: ['cart.component.css'],
      providers: [CartService]
    })

    export class CartComponent implements OnInit{
      public cart: Item[];
      constructor(private cartService:CartService){
        this.cartService.getCart().then(cart => this.cart = cart);
        if (!this.cart)
          console.log('error getting cart');
        else console.log(this.cart.length + ' got cart');
      }
      ngOnInit(){

      }
    }

我遇到的问题是,每当我从另一个组件向购物车添加Item时,它都会正确显示服务中cart的长度(console.log('cart size: ' + this.cart.length);)但是一旦我加载组件(触发组件的构造函数),同样console.log()将打印数组为0,无论我添加了多少项。在cart.component.ts内,if (!this.cart) console.log('error getting cart');也会从通话中触发:this.cartService.getCart().then(cart => this.cart = cart);。我看了很多教程,甚至试过别人的购物车服务,并没有太多运气。

1 个答案:

答案 0 :(得分:1)

不要在注射它的任何地方提供CartService。这导致每个组件都获得自己的实例

@Component({
  moduleId: module.id,
  selector: 'sd-cart',
  templateUrl: 'cart.component.html',
  styleUrls: ['cart.component.css'],
  providers: [CartService] // <<<== remove here
})

仅将服务添加到@NgModule()的提供商。这些提供程序在应用程序根范围中提升,只存在一个实例并传递给依赖它的每个构造函数。

注意:延迟加载的模块有自己的根范围,提供程序不会被提升到应用程序根范围。