简体   繁体   English

如何从 Angular 中的子路由组件访问父组件属性?

[英]How to access parent component properties from a child route component in Angular?

I'm new to Angular and I'm stuck there.我是 Angular 的新手,我被困在那里。 I know how to share data between parent and child components simply by injecting [parentData]="var" into the child selector <>.我知道如何简单地通过将 [parentData]="var" 注入子选择器 <> 来在父组件和子组件之间共享数据。

But when using routing;但是在使用路由时; I only have a router-outlet and can't bind [parentData] to it as it throws an error.我只有一个路由器插座,无法将 [parentData] 绑定到它,因为它会引发错误。

What is the best and easiest way to access parent properties from a child's route?从子路由访问父属性的最好和最简单的方法是什么?

The project is on stackblitz here .该项目在stackblitz上。

I need to display products (from the parent component) inside the child component.我需要在子组件内显示产品(来自父组件)。

version:(Angular 5)版本:(角度5)

Yes this is pretty simple, when you want to pass to component that are in router-outlet you need to use services , actually that component do not exist in the template before you go to the right path, so usual bindings don't work here.是的,这很简单,当你想传递给router-outlet中的组件时,你需要使用services ,实际上在你转到正确的路径之前,模板中不存在该组件,所以通常的绑定在这里不起作用.

So the best way to work this around is to create some simple service所以解决这个问题的最好方法是创建一些简单的服务

In the service在服务中

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

@Injectable()
export class DataTransferService {

  private products= new BehaviorSubject<any>([]);
  cast= this.products.asObservable();

  sendAnything(data) {
    this.products.next(data);
  }

}

then inject your service into both constructors of your parent and child component然后将您的服务注入父组件和子组件的构造函数

In parent component在父组件中

 constructor(private dataTransfer: DataTransferService){}

then create a method然后创建一个方法

 shareData(data){
    this.dataTransfer.sendAnything(data) // to send something
}

and call it from the parent.component.html with并从 parent.component.html 调用它

(click)="shareData(data)" // data is the parent data that you want to share

In child component在子组件中

inside the ngOnInit method add:在 ngOnInit 方法中添加:

 ngOnInit() {
   this.dataTransfer.products.subscribe(res=> this.var = res) // var is the property that you want to assign the data to it.
 }

to get the data and work with it.获取数据并使用它。
more info and examples You can find in doc更多信息和示例您可以在文档中找到

On the one hand, you can not pass an input to the router-outlet tag since the component added by the router will be a sibling to the tag and won't replace it.一方面,您不能将输入传递给 router-outlet 标签,因为路由器添加的组件将是该标签的同级组件,不会替换它。

On the other, When your Angular application becomes more and more complex, passing the same input from the parent components to the child ones will no longer be the right way to do things..另一方面,当您的 Angular 应用程序变得越来越复杂时,将相同的输入从父组件传递给子组件将不再是正确的做事方式。

In your case, the best way to deal with the products variable is to declare it as a behavior subject in the products service:在您的情况下,处理 products 变量的最佳方法是将其声明为 products 服务中的行为主题:

   prodcuts:Subject<IProducts[]> = new BehaviorSubject<IProducts[]>([]);

and in the parent component, you send the received data:在父组件中,您发送接收到的数据:

ngOnInit() { 
    this._productsService.getProducts()
        .subscribe(
          data => {this.products = data;
          this._productsService.prodcuts.next(data);
          },
          error => this.errMsg = error
        );    
}

Finally, in the child client you have to subscribe to the behavior subject declared in the service:最后,在子客户端中,您必须订阅服务中声明的行为主题:

export class ChildComponent implements OnInit {
public products = [];

constructor(private _productsService: ProductsService ) { 
}

ngOnInit() {
    this._productsService.prodcuts
    .subscribe(
      data => {
       {this.products = data;
      }
    );    
  } 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM