将数据从子组件传递到父组件(通过路由加载子组件) [英] Passing data from child to parent component ( child loaded via routing)

查看:33
本文介绍了将数据从子组件传递到父组件(通过路由加载子组件)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个问题.

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

Chat is a parent component and it has Messages child component. I have url-s, /chat/, /chat/:id. So i can get :id param in Messages component with RouteParams, but i need that :id in Chat component. So if i load /chat/46 then Chat component knows that 46 :id

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

If i am loading it as directive something like <messages (Event)="handleEvent()"></messages> than i can pass it via EventEmitter and Output, but if i load component through <router-outlet> how i can pass value back to the parent ? EventEmitter and Output doesn't work in this case. Maybe there is something in router that can do the trick.

推荐答案

您可以按照建议通过组件之间的交互来实现.下面是一个例子:

You can do this by interaction between components as suggested. Here is an example:

component-interaction.service.ts

component-interaction.service.ts

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

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

messages.component.ts

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

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 更改,并且父母每次都可以得到它.

This way the id changes are subscribed and parent can preety much get it every time.

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

Changed the EventEmitter to Subject and asObservable combo as advised by Angular team and added unsubscribe to avoid memory leak.

这篇关于将数据从子组件传递到父组件(通过路由加载子组件)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆