【问题标题】:Passing data from child to parent component ( child loaded via routing)将数据从子组件传递到父组件(通过路由加载子组件)
【发布时间】:2016-09-05 23:32:00
【问题描述】:

我有这个问题。

Chat 是一个父组件,它有 Messages 子组件。我有 url-s、/chat//chat/:id。所以我可以使用 RouteParamsMessages 组件中获取 :id 参数,但我需要在 Chat 组件中使用 :id。因此,如果我加载 /chat/46 然后 Chat 组件知道 46 :id

如果我将它作为指令加载,例如 <messages (Event)="handleEvent()"></messages>,我可以通过 EventEmitter 和输出传递它,但是如果我通过 <router-outlet> 加载组件,我如何将值传递回父级? EventEmitter 和 Output 在这种情况下不起作用。也许路由器中的某些东西可以解决问题。

【问题讨论】:

  • 嗯,这是个好主意,但它不起作用。聊天组件有订阅但不提供任何数据,所以 .subscribe(resp => console.log(resp)) 什么也不显示。 @GünterZöchbauer
  • 现在工作的是 router.isActive(),我在模板中使用它,但我需要类中的数据。 isActive() 也绑定到属性并不断调用,正如我在日志中看到的那样,所以这不是我猜的最佳解决方案。通常将函数绑定到 Angular2 中的属性是个坏主意,因为非常复杂的更改检测引擎会强制经常调用该函数。
  • 这里是 plnkr plnkr.co/edit/y7PZONWELeG4f2Ywbw4k - 很奇怪,它不起作用,因为消息传递适用于返回 observable 的 http 请求。 @GünterZöchbauer

标签: angular angular2-routing


【解决方案1】:

您可以按照建议通过组件之间的交互来做到这一点。 这是一个例子:

组件交互.service.ts

id = new Subject<number>();
idEmitter$ = this.id.asObservable();

sendId(id:number){
    this.id.next(id);
}

messages.component.ts

constructor(private router:Router, private cci:ComponentInteractionService){}

ngOnInit(){
    this.cci.sendId(this.router.param); // sending your params the way you get it
}

chat.component.ts

id:number;
subscription: Subscription;

constructor(private cci:ComponentInteractionService){}

ngOnInit(){
    this.subscription = this.cci.idEmitter$.subscribe(res =>this.id = res);
}

ngOnDestroy(){
    this.subscription.unsubscribe();
}

通过这种方式订阅 id 更改,父母每次都能轻松获得它。

编辑:按照 Angular 团队的建议将 EventEmitter 更改为 Subject 和 asObservable 组合,并添加了取消订阅以避免内存泄漏。

【讨论】:

    【解决方案2】:

    您应该考虑使用依赖注入在 Chat(父)和 Message(子)中注入 SessionService 实例(始终是同一个实例)。

    当 Child 有一个值要与 Parent 通信时,它可以将其存储到 SessionService 中;如果 SessionService 实例是相同的(这是由标准的依赖归纳使用授予的),那么 Parent 应该能够捕获 Child 想要通信的内容。

    希望对你有帮助

    【讨论】:

    • 您好,它不起作用。更改后的值未定义。
    猜你喜欢
    • 2016-08-28
    • 1970-01-01
    • 2019-02-27
    • 2017-04-20
    • 1970-01-01
    • 2020-10-22
    • 2017-06-10
    相关资源
    最近更新 更多