【发布时间】:2019-11-16 19:02:07
【问题描述】:
我正在使用angular(最新版本)建立一个网站,但我的问题是来自RxJS 的BehaviorSubject 不起作用
service.service.ts
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
export class ServicesService {
constructor() {
this.getCartList()
} productObj
private productObj = new BehaviorSubject({'total':0,'products':[]})
get getTheNo(){
return localStorage.getItem('cartNo') ? parseInt(localStorage.getItem('cartNo')) : 0
}
get getCartItemCount() {
return this.cartItemCount;
}
get getCartItemPop() {
return this.productObj;
}
getCartList(){
.......
......
this.productObj.value.products.push({'id':cookarfg[0],'name':cookarfg[2],'amount':cookarfg[2],'price':cookarfg[3],'pics':cookarfg[4]})
this.productObj.value.total=cookarfg[3]
this.productObj.next(this.productObj.value);
}
}
这里是 header.components.ts 的代码
import { Component, OnInit } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
import { ServicesService } from '../../services/services.service'
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {
productObj: BehaviorSubject<any>;
constructor(
private service: ServicesService,
) { }
ngOnInit() {
this.productObj = this.service.getCartItemPop;
console.log('console-> ',this.service.getCartItemPop)
}
}
我想要的是,每当页面加载时,它将productObj 更新为最新值而不是{'total':0,'products':[]},但它不起作用。我尝试了所有方法,但仍然无法正常工作,我需要您的帮助,我还是 angular 的新手,谢谢
【问题讨论】:
-
首先你在
getCartList()中做奇怪的事情,你在操纵value的BehaviorSubject,这不是怎么做的。文档中有一个如何实现此模式的示例,它应该对您有所帮助:angular.io/guide/… -
另一件事是您似乎定义了 2 个 projectObj (!?)
productObj private productObj
标签: angular rxjs behaviorsubject