【问题标题】:Access variable from one component into another将变量从一个组件访问到另一个组件
【发布时间】:2017-11-22 14:48:24
【问题描述】:

我正在尝试做一些 Angular 项目,但我不参与 Web 开发。它的简单商店。
我想通过 Play Framework 从 sqlite 获取一些信息。这是工作。

在我收到它的角度和显示后。 它也可以工作。服务:

@Injectable()
export class ProductService {

constructor(private http: Http) { }

getProducts() {
  const headers: Headers = new Headers();
  headers.append('Accept', 'application/json');
  headers.append('Content-Type', 'application/json');

  const options = new RequestOptions({headers: headers});

  return this.http.get('http://localhost:9900/', options)
  .map(response => <Product[]>response.json());
 } 
}

当我拿走所有产品的时候:

export class ProductComponent implements OnInit {

public products: Product[];
actualProduct: Product;
productForm: FormGroup;
public quantity: number;
private activeFilter: string = "reset";
public allFilters: Array<string>;


constructor(private productService: ProductService,private router:Router) {
  this.allFilters =  ['ocean', 'river', 'aquarium', 'reset'];
}

ngOnInit() {
  this.productService.getProducts().subscribe(data => this.products = data);
}

public getActualProduct() {
  return this.actualProduct;
}

clickedProduct(product) {
  this.actualProduct = product;
  let link = ['/detail', product.prodId];
  this.router.navigate(link);
}

public setFilter(filter: string) {
 this.activeFilter = filter;
 }
}

所以我的问题是:如何访问其他组件中的数组产品?因为现在,当我单击具有 clickedProduct 功能的按钮时,它的工作完美。它显示在控制台对象产品中。但是当我尝试使用产品在其他组件中显示产品详细信息时,我失败了:

 export class ProductDetailComponent implements OnInit {

 selectedProduct: Product;
 products: Product[];
 quantity: number;

 constructor(
 private productService:ProductService,
 private productComponent: ProductComponent,
 private route:ActivatedRoute,
 private location:Location,
  // private cartStore: CartStore
 ) {  }

ngOnInit() {
    this.selectedProduct = this.productComponent.getActualProduct();
}

addToCart(product) {
  console.log(this.selectedProduct)
  console.log(product)
  //this.cartStore.addToCart(product, this.quantity || 1)
}

goBack() {
    this.location.back()
 }
}

如何在 ProductDetailComponent 中获取实际产品变量,或者如何获取所有产品的数组? 我尝试在 productComponent 中使用“@Input() actualProduct: Product”,但它实际上不起作用。 感谢您的帮助。

【问题讨论】:

  • 组件之间是否存在父子关系?还是以不同的路线呈现?
  • 如果您的问题是关于 Angular 的,请添加 angular 标签。

标签: angular typescript angular2-components


【解决方案1】:

这与这些组件相互关联的方式密切相关。

如果存在父子关系,可以通过@Input属性向子组件传递信息,通过@Output属性监听父组件中的子事件.

如果组件之间不存在这种关系(例如路由组件),那么最常见的选择是创建一个管理信息/事件流的服务组件之间。

更多信息请查看the docs

【讨论】:

  • 它们以两种不同的路线呈现。我现在明白了,为什么我尝试过时不能使用 @Input() 。创建服务只是为了传递一个数组好吗?因为这实际上就是我所需要的。
  • 是的,您需要将该数组封装在服务中,并提供更新、重置和获取它的功能。检查此部分angular.io/guide/…
  • 谢谢!我会尝试这样做;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-01-05
  • 2016-09-16
  • 1970-01-01
  • 2017-10-10
  • 1970-01-01
  • 2020-07-23
  • 1970-01-01
相关资源
最近更新 更多