简体   繁体   English

Angular 2-在服务之间共享数据

[英]Angular 2 - share data between services

I have two components and 2 services connected to them. 我有两个组件和与其连接的2个服务。 First is a ProductComponent : 首先是一个ProductComponent

@Component({
  selector: 'app-product',
  templateUrl: './product.component.html',
  styleUrls: ['./product.component.css'],
  providers: [ProductService, CartService]
})
export class ProductComponent implements OnInit {
  private products;
  private numberOfItems = 0;

  constructor(private productService: ProductService, private cartService: CartService) {
  }

  ngOnInit() {
    this.loadProducts();
  }

  loadProducts() {
    this.productService.getProducts().subscribe(data => this.products = data);
  }

  addProductToCard(product: Product) {
    this.cartService.addProduct(product);
    this.numberOfItems = this.cartService.getCartLength();
  }
}

I use here CartService where I saved products I want to buy. 我在这里使用CartService保存我要购买的产品。 All of them are add into cart list which is defined in CartService : 所有这些都添加到CartService定义的cart列表中:

@Injectable()
export class CartService {
  private cart: Product[] = [];

  constructor() {
  }

  addProduct(product: Product) {
    this.cart.push(product);
  }

  getCart() {
    return this.cart;
  }

  getTotalPrice() {
    const totalPrice = this.cart.reduce((sum, cardItem) => {
      return sum += cardItem.price, sum;
    }, 0);
    return totalPrice;
  }

  getCartLength() {
    return this.cart.length;
  }
}

export interface Product {
  id: number;
  name: string;
  description: string;
  price: number;
  amount: number;
}

Now I want to use this filled cart list in CartComponent : 现在,我要在CartComponent使用此已填充的cart列表:

@Component({
  selector: 'app-card',
  templateUrl: './card.component.html',
  styleUrls: ['./card.component.css']
})
export class CartComponent implements OnInit {

  private cart;

  constructor(private cartService: CartService) {
  }

  ngOnInit() {
    this.cart = this.cartService.getCart();
    console.log(this.cart.length);
  }    
}

but it is empty there. 但那里是空的。 I know that probably I inject there new CartService , not that one I used in ProductComponent . 我知道我可能在那里注入了新的CartService ,而不是我在ProductComponent使用的那个。 My question is how to use same instance of CartService in CartComponent as I use in ProductComponent ? 我的问题是如何在CartComponent中使用与ProductComponent使用的CartService相同的实例? Or how to share data between this two services? 还是如何在这两种服务之间共享数据? Maybe I should use cache for this but I hope there are other ways to solve this problem. 也许我应该为此使用缓存,但是我希望还有其他方法可以解决此问题。

EDIT: I add html where I call addToProduct() : 编辑:我在调用addToProduct()地方添加html:

<div class="basket">
  On your cart {{numberOfItems}} items
  <p><a routerLink="/cart">Go to cart</a></p>
  <router-outlet></router-outlet>
</div>

<table class="table table-striped">
  <thead class="thead-inverse">
  <tr>
    <th>#</th>
    <th>Name</th>
    <th>Desc</th>
    <th>Price</th>
    <th>Amount</th>
  </tr>
  </thead>
  <tbody *ngFor="let product of products">
  <tr>
    <th scope="row">{{product.id}}</th>
    <td>{{product.name}}</td>
    <td>{{product.description}}</td>
    <td>{{product.price}}</td>
    <td>{{product.amount}}</td>
    <button type="button" class="btn btn-success" (click)="addProductToCard(product)">Add to cart</button>
  </tr>
  </tbody>
</table>

如果要在两个组件中都获得CartService的相同实例, CartService必须将其注册为模块级提供程序,而不是单个组件上的提供程序。

Sharing data between services is better approch. 在服务之间共享数据更好。 Instead use ngrx/store package which is similar to Redux. 而是使用类似于Redux的ngrx / store软件包。

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

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