I'm facing undefined data outside of subscribe, but it's getting inside of subscribe. I know, it's because of the Observable behavior. But how can I resolve this?
edit.ts
ngOnInit(): void {
let product
this.productId = this.route.snapshot.paramMap.get('id')
if (this.productId) {
this.productService
.getProductDetails(this.productId)
.subscribe((response) => {
product = response.data
console.log(product)
})
}
console.log(product)
this.form = new FormGroup({
productName: new FormControl(null, Validators.required),
type: new FormControl(null, Validators.required),
model: new FormControl(null)
})
}
service.ts
getProductDetails(id: string) {
return fromFetch(`http://localhost:3000/product/${id}`).pipe(
switchMap((response) => {
if (response.ok) {
return response.json()
} else {
return of({ error: true })
}
})
)
}
Here, I want to access the product outside of subscribe.