I am working in an Angular 4 application,In this I am passing product name from (landingpage.component.ts)one component to Service file when the user clicked on the particular product.In service file I am getting the product image path from API by passing the product name.Then I am passing that image path to (my-car.component.ts)another component.But in my-cart component I got the path name as undefined.
component - service -component
Landingpage.component.ts
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { CartdataService } from '../../services/cartdata.service';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-landingpage',
templateUrl: './landingpage.component.html',
styleUrls: ['./landingpage.component.css']
})
export class LandingpageComponent {
product_Name: any;
ngOnInit() { }
constructor(private CartdataService: CartdataService, private router: Router{}
getProductName(Pname: any) {
this.CartdataService.get_Product_Path(Pname.textContent);
}
}
cartdata.service.ts
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class CartdataService {
public product_Path = new BehaviorSubject<any>('');
cast_Product_Path = this.product_Path.asObservable();
current_product : any;
path :any;
constructor(private http: HttpClient) { }
get_Product_Path(pName : string)
{
this.current_product = pName.trim();
this.http.get(`http://localhost:abc/api/data/GetImage/?
imageName=${this.current_product}`)
.subscribe(data =>this.path = data[0]['Image_PATH_NAME'])
this.product_Path.next(this.path);
}
}
My-cart.component.ts
import { Component,EventEmitter,Output } from '@angular/core';
import { Router } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import {CartdataService} from '../../services/cartdata.service';
import {Http} from '@angular/http';
@Component({
selector: 'app-my-cart',
templateUrl: './my-cart.component.html',
styleUrls: ['./my-cart.component.css'],
outputs :['ChildEvent']
})
export class MyCartComponent {
path:any;
constructor(private CartdataService :CartdataService,private router:Router,private http: HttpClient) {}
ngOnInit() {
this.CartdataService.cast_Product_Path.subscribe(product_Path=> this.path = product_Path);
}
}
In this component I am trying to get the path but receiving "undefined",I am new to angular4 ,please guide me to solve this .
Thanks.
You must use this.product_Path.next(this.path)
inside subscribe
in your service
...
.subscribe(data => {
this.path = data[0]['Image_PATH_NAME'])
this.product_Path.next(this.path);
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.