我一直试图在html组件中显示数据,但我面临的问题是,当我输入第一个值后转到该组件时,它会正确显示,第二次我输入值并检索它们时第一个值正确显示,但第二个值显示2次,类似地,我第三次输入值并检索它们,第一个值显示1次,第二个值显示2次,第三个值显示3次,对不起,该问题或解释可能很傻,所以我在这里向您展示屏幕截图
下面是代码
component.ts文件
import { Component, OnInit } from '@angular/core';
import { Productservice } from 'src/app/services/products.service';
import { Router, ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-admin-products',
templateUrl: './admin-products.component.html',
styleUrls: ['./admin-products.component.scss']
})
export class AdminProductsComponent implements OnInit {
listofproducts
constructor(private prservice:Productservice,private
router:Router,private route:ActivatedRoute) {
}
ngOnInit() {
this.listofproducts=this.prservice.getallproducts()
console.log(this.listofproducts)
}
}
另一个组件
import { Component, OnInit } from '@angular/core';
import { Productservice } from 'src/app/services/products.service';
import { Router, ActivatedRoute } from '@angular/router';
import { Subscription } from 'rxjs';
@Component({
selector: 'app-new-card',
templateUrl: './new-card.component.html',
styleUrls: ['./new-card.component.scss']
})
export class NewCardComponent implements OnInit {
subscription:Subscription
cardvalue
constructor(private
prservice:Productservice,router:Router,route:ActivatedRoute) { }
ngOnInit() {
this.subscription=this.prservice.productcard.subscribe(
(value)=>{
this.cardvalue=value
// console.log(this.cardvalue)
this.prservice.addtocardarray(this.cardvalue)
}
)
}
}
服务文件
import { Subject } from "rxjs";
export class Productservice{
productcard=new Subject<[]>()
cards=[]
addtocardarray(value){
this.cards.push(value)
// console.log(this.cards)
}
getallproducts(){
return this.cards
}
}
答案 0 :(得分:1)
问题出在这行代码中:
this.prservice.productcard.subscribe((value) =>
...
this.prservice.addtocardarray(this.cardvalue)
)
您要在每个新组件中订阅productcard而不取消订阅,这意味着如果您有3个组件并且productcard发出val,addtocardarray(val)
将被调用3次
您应在订阅前添加.pipe(take(1))
。
https://www.learnrxjs.io/operators/filtering/take.html