Angular 如何使用observable更新阵列,以及如何在网站负载上初始化observable?

Angular 如何使用observable更新阵列,以及如何在网站负载上初始化observable?,angular,angular7,angular-observable,angular-lifecycle-hooks,angular-ngfor,Angular,Angular7,Angular Observable,Angular Lifecycle Hooks,Angular Ngfor,我有两个组件“购物车”和“家”。这里“主页”组件显示产品列表,它是网站的第一页。当有人使用“购物车”按钮将产品添加到购物车时,我想更新购物车。为此,我创建了一个服务,使用observable将消息从“home”发送到“cart”组件 我面临的问题: 1. *使用observable更新阵列时,ngFor未更新。 2.当我在ngOnInit()上初始化observable时,cart数组只有在我至少访问一次cart组件时才会更新 home.component.ts cart.service.ts

我有两个组件“购物车”和“家”。这里“主页”组件显示产品列表,它是网站的第一页。当有人使用“购物车”按钮将产品添加到购物车时,我想更新购物车。为此,我创建了一个服务,使用observable将消息从“home”发送到“cart”组件

我面临的问题: 1. *使用observable更新阵列时,ngFor未更新。 2.当我在ngOnInit()上初始化observable时,cart数组只有在我至少访问一次cart组件时才会更新

home.component.ts

cart.service.ts

cart.component.html

    {{item}}

我尝试了“ChangeDetectorRef”、markForCheck()和detectChanges(),但都不起作用。

使用行为主题:

private productIdSource = new BehaviorSubject<string>();
productId$ = this.productIdSource.asObservable(); 

constructor() { }

sendId(id:string) {
   this.productIdSource.next(id);
}
private productIdSource=new BehaviorSubject();
productId$=this.productIdSource.asObservable();
构造函数(){}
sendId(id:string){
this.productIdSource.next(id);
}

使用行为主体

private productIdSource = new BehaviorSubject<string>();
productId$ = this.productIdSource.asObservable(); 

constructor() { }

sendId(id:string) {
   this.productIdSource.next(id);
}
private productIdSource=new BehaviorSubject();
productId$=this.productIdSource.asObservable();
构造函数(){}
sendId(id:string){
this.productIdSource.next(id);
}

尝试覆盖
itemList
而不是变异:

this.addtocart.productId$.subscribe(
    msg => {
      this.itemList = [...this.itemList, msg]; // instead of this.itemList.push(msg);
    }
  )

尝试覆盖
itemList
,而不是改变:

this.addtocart.productId$.subscribe(
    msg => {
      this.itemList = [...this.itemList, msg]; // instead of this.itemList.push(msg);
    }
  )

你能在StackBiltz中共享吗?你能在StackBiltz中共享吗?Array正在像往常一样更新,但不是*ngFor。这也是我访问购物车组件至少一次的时候。数组像往常一样更新,但不是*ngFor。这也是我至少访问购物车组件一次的时候。BehaviorSubject可以工作,但它只能用于添加一个项目。您将一次向购物车添加一个项目,对吗?从productlist中,用户可以单击“+购物车”按钮添加多个项目,但数量是一个。确定。。您可以在StackBiltzBehavior子对象中共享它,但它只能用于添加一个项目。您将一次向购物车添加一个项目,对吗?从productlist中,用户可以单击“+购物车”按钮添加多个项目,但数量是一个。确定。。你能和斯塔克比尔茨分享吗
private productIdSource = new BehaviorSubject<string>();
productId$ = this.productIdSource.asObservable(); 

constructor() { }

sendId(id:string) {
   this.productIdSource.next(id);
}
this.addtocart.productId$.subscribe(
    msg => {
      this.itemList = [...this.itemList, msg]; // instead of this.itemList.push(msg);
    }
  )