我正在开发一个应用程序,我正在从服务订阅更改,但不知何故它没有检测到更改,我没有收到最新数据,有人可以告诉我我在哪里丢失。
基本上它是一个购物车应用程序,我正在用产品推车。
我订阅的组件发生了变化..
import { Component, OnInit, ChangeDetectorRef } from '@angular/core';
import { CartService } from '../services/cart.service';
import { Subscription } from 'rxjs/Subscription';
@Component({
selector: 'app-cart-observer',
templateUrl: './cart-observer.component.html',
styleUrls: ['./cart-observer.component.css'],
providers: [CartService]
})
export class CartObserverComponent implements OnInit {
products: any[] = [];
numProducts: number = 0;
cartTotal: number = 0;
changeDetectorRef: ChangeDetectorRef;
constructor(private cartService: CartService, changeDetectorRef: ChangeDetectorRef) {
this.changeDetectorRef = changeDetectorRef;
}
ngOnInit() {
this.cartService.productAdded$$.subscribe(data => {
console.log(data);
this.products = data.products;
this.cartTotal = data.cartTotal;
console.log(this.products);
this.changeDetectorRef.detectChanges();
});
}
deleteProduct(product) {
this.cartService.deleteProductFromCart(product);
}}
购物车服务:我推动变更的组件
import { Injectable } from '@angular/core';
import { Product } from '../product-list/product';
import { Subject } from 'rxjs/Subject';
@Injectable()
export class CartService {
products: any[] = []
cartTotal: number = 0
private productAddedSource = new Subject<any>()
productAdded$$ = this.productAddedSource.asObservable();
constructor() { }
addProductToCart(product) {
console.log(product);
let exists = false;
let parsedPrice = product.price;
this.cartTotal += parsedPrice
//Search this product on the cart and increment the quantity
this.products = this.products.map(_product => {
if (_product.product.id == product.id) {
_product.quantity++
exists = true
}
return _product
})
//Add a new product to the cart if it's a new product
if (!exists) {
product.parsedPrice = parsedPrice
this.products.push({
product: product,
quantity: 1
})
}
console.log(this.products);
this.productAddedSource.next({ products: this.products, cartTotal: this.cartTotal });
}
deleteProductFromCart(product) {
this.products = this.products.filter(_product => {
if (_product.product.id == product.id) {
this.cartTotal -= _product.product.parsedPrice * _product.quantity
return false
}
return true
})
this.productAddedSource.next({ products: this.products, cartTotal: this.cartTotal })
}
flushCart() {
this.products = []
this.cartTotal = 0
this.productAddedSource.next({ products: this.products, cartTotal: this.cartTotal })
}
}
答案 0 :(得分:1)
感谢评论人员,我在删除时解决了
providers: [CartService]
来自我订阅更改的组件。