繁体   English   中英

如何将值从同级组件传递到角度6中的路由器出口?

[英]How to pass value from a sibling component to router outlet in angular 6?

app.component.html:

<app-navbar>...router links here</app-navbar>
<app-controller>...contains multiple inputs</app-controller>
<router-outlet>... renders n pages </router-outlet>

如何在<router-outlet>子页面的<controller>组件(可由用户更改)中使用动态数据? controller component构建需要在所有页面之间共享的数据。 每个页面基于控制器组件数据呈现不同形式的表。

我尝试了eventEmitter@input @outputs但不是为这个层次结构而为父母和孩子工作的。 使用服务也不适用于动态数据。 我不确定这种要求的基准是什么。

为了在angular.js中实现此目的,我将控制器组件包含到每个页面组件中,并通过$rootScope传递其数据,并添加$rootScope.$watch如果我想查看它们是否已更改)。

您可以从RX js开始使用主题或行为主题 ,否则您可以一次更新多个组件的数据,请查找一些示例

// Behavior Subject

// a is a initial value. if there is a subscription 
// after this, it would get "a" value immediately
let bSubject = new BehaviorSubject("a"); 

bSubject.next("b");

bSubject.subscribe((value) => {
  console.log("Subscription got", value); // Subscription got b, 
                                          // ^ This would not happen 
                                          // for a generic observable 
                                          // or generic subject by default
});

bSubject.next("c"); // Subscription got c
bSubject.next("d"); // Subscription got d

// Regular Subject

let subject = new Subject(); 

subject.next("b");

subject.subscribe((value) => {
  console.log("Subscription got", value); // Subscription wont get 
                                          // anything at this point
});

subject.next("c"); // Subscription got c
subject.next("d"); // Subscription got d

为此使用服务。 在需要共享数据的所有页面中使用它,并在app.component提供它,以便控制器和render-outlet将共享同一服务实例。

在应用程序组件中:

@Component({
  ...,
  provide: [SharedDataService],
})
export class AppComponent {
}

在孩子们中:

constructor(
  sharedDataService : SharedDataService,
) { }

Angular建议采用这种方式来处理组件之间的通信。

暂无
暂无

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

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