[英]Angular 2 - share data between services
我有兩個組件和與其連接的2個服務。 首先是一個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();
}
}
我在這里使用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;
}
現在,我要在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);
}
}
但那里是空的。 我知道我可能在那里注入了新的CartService
,而不是我在ProductComponent
使用的那個。 我的問題是如何在CartComponent
中使用與ProductComponent
使用的CartService
相同的實例? 還是如何在這兩種服務之間共享數據? 也許我應該為此使用緩存,但是我希望還有其他方法可以解決此問題。
編輯:我在調用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
必須將其注冊為模塊級提供程序,而不是單個組件上的提供程序。
在服務之間共享數據更好。 而是使用類似於Redux的ngrx / store軟件包。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.