我正在尝试使用updatecardproducts.component.ts
通过主题将数据从updateproducts.component.ts传递到.pipe(take(1))
我面临的问题是,当我单击父组件的编辑按钮时(它会将我导航到更新产品组件),将我带到更新产品组件,但是在控制台中我第一次看不到任何内容但是,如果再次单击,我得到结果,然后一切正常,问题就只有我第一次单击“编辑”按钮时才存在。下面是代码
updateproducts.component.ts
export class UpdateproductsComponent implements OnInit {
recipeform:FormGroup
id:number
product
editmode=false
constructor(private route:ActivatedRoute,private
router:Router,private prservice:Productservice) { }
ngOnInit() {
this.route.params.subscribe(
(params)=>{
this.id=+params['id']
if(params['id']!=null){
this.editmode=true
}
this.initform()
})
}
private initform(){
let title=''
let price=''
let select=''
let imageurl=''
if(this.editmode){
const product=this.prservice.getproductbyid(this.id)
title=product.title
price=product.price
select=product.select
imageurl=product.imageurl
this.prservice.updatedproduct.next(product)
//this is the values i am trying to pass
}
this.recipeform=new FormGroup({
'title':new FormControl(title,Validators.required),
'price':new FormControl(price,Validators.required),
'select':new FormControl(select,Validators.required),
'imageurl':new FormControl(imageurl,Validators.required)
})
}
}
products.service.ts
import { Subject } from "rxjs";
export class Productservice{
updatedproduct=new Subject<any>()
card=new Subject<any>()
cards=[]
addtocards(value){
this.cards.push(value)
// console.log(this.cards)
// console.log(this.cards[0])
}
getallproducts(){
return this.cards
}
getproductbyid(id){
// console.log(this.cards[id])
return this.cards[id]
}
updateproduct(id,product){
return this.cards[id]=product
// this.updatedproduct.next(this.cards.slice())
}
}
updateproducts.component.ts
export class UpdatecardproductsComponent implements OnInit {
subscription:Subscription
carddetails
constructor(private prservice:Productservice) { }
ngOnInit() {
this.subscription=this.prservice.updatedproduct.pipe(take(1))
.subscribe(
(value)=>{
this.carddetails=value
console.log(this.carddetails)
}
)
}
}
因此,首先呈现此组件时,我在控制台中看不到任何东西(this.carddetails),但是从第二次起,一切正常,并在控制台中显示