I am trying to pass data from updateproducts.component.ts to updatecardproducts.component.ts
via Subject using .pipe(take(1))
The issue I am facing is that when I click on edit button of parent component(it justs navigates me to the update products component) it takes me to the update products component but in console I do not see anything for the first time but then again if I click I get the result and then after it everything works fine, the problem exists for only the first time I click on edit button . Below is the code
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)
}
)
}
}
so first when this component is rendered I do not see anything(this.carddetails) in the console but after that from second time onwards everything works fine and gets displayed in the console