[英]How to transfer data between component Angular?
How to transfer data between component Angular when they are more than one nesting? 当多个嵌套时,如何在组件Angular之间传输数据?
For example: 例如:
<router-outlet> </router-outlet>
<filter-mobile></filter-mobile>
I need pass outcome data from component filter-mobile
to any component inside <router-outlet> </router-outlet>
it can be also nested component. 我需要将结果数据从组件
filter-mobile
传递到<router-outlet> </router-outlet>
内的任何组件,它也可以是嵌套组件。
If you need more explanations, please leave comment 如果您需要更多说明,请发表评论
The best practice for this is to have the component where you combine these two parts (in the HTML), act as a Smart Component
and manage the data flows between the two. 最佳做法是使组件结合在一起(在HTML中)这两个部分,充当
Smart Component
并管理两者之间的数据流。 You could also provide
a service
on this level that the underlaying components can (Optionally?) inject as well and communicate through that. 您还
provide
在此级别provide
一项service
,底层组件也可以(可选地)注入并通过该服务进行通信。 You will have to think about the data that will pass through there, but it's another way you can achieve it. 您将不得不考虑将通过那里的数据,但这是实现它的另一种方式。
Especially when the filter-mobile
component
is the source of the events you are interested in, you can have a more tightly connected service to that component where it emits it's events to. 尤其是当
filter-mobile
component
是您感兴趣的事件的来源时,您可以将与之紧密联系的服务发送到该组件,并向其发送事件。 The components depending on your router will then (optionally) have to listen to this service and act on its messages. 然后,取决于您的路由器的组件将(可选)必须侦听此服务并对其消息采取行动。
https://angular.io/guide/component-interaction#parent-and-children-communicate-via-a-service https://angular.io/guide/component-interaction#parent-and-children-communicate-via-a-service
The "best" way is using services .You can use the services to communicate between the different components. “最佳”方式是使用服务。您可以使用服务在不同组件之间进行通信。
import { Injectable } from '@angular/core';
@Injectable()
export class ShareableServiceService {
/**
* Choose your dataType
*/
public shareableData: BehaviorSubject<any> = new BehaviorSubject()
constructor() {
}
public updateData(newContent: any): void {
this.shareableData.next(newContent);
}
}
//COMPONENT
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular';
constructor(private service: ShareableServiceService) {
this.service.shareableData.subscribe(data => {
//DO SOMETHING TO YOUR DATA HERE
});
}
You Should set all these data up to a service class. 您应该将所有这些数据设置为服务类。
1 - create a behaviorSubject atribuite and share all over your components 1-创建一个BehaviorSubject属性并共享您的所有组件
You can share data between different components using a service to store/pass the data around. 您可以使用服务存储/传递数据,从而在不同组件之间共享数据。
Basically, you should: 基本上,您应该:
I created an oversimplified example here (stackblitz) 我在这里创建了一个过于简化的示例(stackblitz)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.