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

shi*_*tab 7 javascript routing parent-child angular

版本:(角度5)

我是Angular的新手,但我一直呆在那里。我知道如何通过将[parentData] =“ var”注入子选择器<>来简单地在父子组件之间共享数据。

但是当使用路由时;我只有路由器出口,不能将[parentData]绑定到它,因为它会引发错误。

从子路径访问父属性的最佳和最简便方法是什么?

该项目在这里闪电击中

我需要在子组件内部显示产品(来自父组件)。

Kra*_*ken 6

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.

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);
  }

}
Run Code Online (Sandbox Code Playgroud)

then inject your service into both constructors of your parent and child component

In parent component

 constructor(private dataTransfer: DataTransferService){}
Run Code Online (Sandbox Code Playgroud)

then create a method

 shareData(data){
    this.dataTransfer.sendAnything(data) // to send something
}
Run Code Online (Sandbox Code Playgroud)

and call it from the parent.component.html with

(click)="shareData(data)" // data is the parent data that you want to share
Run Code Online (Sandbox Code Playgroud)

In child component

inside the ngOnInit method add:

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

to get the data and work with it.
more info and examples You can find in doc


m.b*_*ali 5

一方面,您无法将输入传递给 router-outlet 标记,因为路由器添加的组件将是该标记的同级组件,并且不会替换它。

另一方面,当你的 Angular 应用程序变得越来越复杂时,将相同的输入从父组件传递给子组件将不再是正确的处理方式。

在您的情况下,处理 products 变量的最佳方法是将其声明为 products 服务中的行为主体:

   prodcuts:Subject<IProducts[]> = new BehaviorSubject<IProducts[]>([]);
Run Code Online (Sandbox Code Playgroud)

在父组件中,您发送接收到的数据:

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

最后,在子客户端中,您必须订阅服务中声明的行为主体:

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

constructor(private _productsService: ProductsService ) { 
}

ngOnInit() {
    this._productsService.prodcuts
    .subscribe(
      data => {
       {this.products = data;
      }
    );    
  } 
}
Run Code Online (Sandbox Code Playgroud)