我正在使用Angular 4应用程序,在此我将产品名称从(landingpage.component.ts)传递给用户点击特定产品时的一个组件。在服务文件中我得到了产品图片通过传递产品名称从API路径。然后我将该图像路径传递给(my-car.component.ts)另一个组件。但是在我的购物车组件中,我将路径名称定义为未定义。
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);
}
}
在这个组件中,我试图获得路径,但接收&#34; undefined&#34;,我是angular4的新手,请指导我解决这个问题。
感谢。
答案 0 :(得分:2)
您必须在服务中使用this.product_Path.next(this.path)
内的subscribe
...
.subscribe(data => {
this.path = data[0]['Image_PATH_NAME'])
this.product_Path.next(this.path);
});