这是我的订阅购物车提供商,其中.cart
可订阅
@Injectable()
export class CartProvider {
cart: Observable<Array<CartItem>>
private _cart: BehaviorSubject<Array<CartItem>>;
private cartStore: Array<CartItem> = [];
constructor(private dialogs: DialogsProvider) {
this._cart = <BehaviorSubject<Array<CartItem>>>new BehaviorSubject([]);
this.cart = this._cart.asObservable();
}
/**
* return obs array cart
*
* @returns {Observable<Array<CartItem>>}
* @memberof CartProvider
*/
getCart(): Observable<Array<CartItem>> {
return this.cart;
}
当我尝试订阅Ionic页面上的更改时,它可以正常工作
export class ItemsPage
@ViewChild(Content) content: Content;
items: Array<CartItem>;
cartDisplay:any;
constructor(public navCtrl: NavController, public navParams: NavParams , private cart:CartProvider
) {
cart.getCart().subscribe((val) => {
this.cartDisplay = val.length;
});
}
但是当我尝试使用相同的方法时cart.getCart()
它无法在CartProvider.cart
上观察更改,因此当相同的确切代码在Ionic Page上工作时,它无法更改自定义组件html上的值/ p>
<button ion-button clear icon-only (click)="showCart()">
<ion-icon name="cart"></ion-icon>
<span class="badge" *ngIf="cartDisplay > 0">{{cartDisplay}}</span>
</button>
答案 0 :(得分:0)
<强> UPDATE :: 强>
我通过将CartProvider添加到CustomComponent提供者数组中来解决此问题
import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { CartComponent } from './cart';
import { CartProvider } from "../../providers/cart/cart";
@NgModule({
declarations: [
CartComponent,
],
imports: [
IonicPageModule.forChild(CartComponent),
],
exports: [
CartComponent
],
providers:[
CartProvider // <-------- added here instead of adding it to component.providers array
]
})
export class CartComponentModule {}