angular - Angular - 如何通过路由将数据从子组件发送到父组件?
问题描述
我想设置一个 SampleData 并将其发送到 Angular 中的父组件。当子组件完全在父组件内部时,它可以正常工作。
但是,我想通过路由在父组件中设置不同的子组件。
所以我把在 parent.component.html 中,子组件是这样调用的,不再起作用了……
{ path: "sample1", component: Sample1Component }
谁能看到我的代码并给我一个解决方案...?
Center 组件将是父组件,Sample1 组件将是子组件。
您可以从此处下载代码以查看更多详细信息
app.router.module.ts
const AppRoutes: Routes = [
{ path: "", redirectTo: "/", pathMatch: "full" },
{ path: "sample1", component: Sample1Component },
{ path: "**", redirectTo: "/", pathMatch: "full" }
];
center.component.html
<div (sampleEvent)="SampleData = $event">
Center Area Title from Sample 1 : {{ SampleData }}
</div>
<!--if sample 1 Component is called by this Router, 'Center Area Title value does not change -->
<router-outlet></router-outlet>
<!-- if sample 1 Component is called by below, 'Center Area Title value changes-->
<!-- <app-sample1 (sampleEvent)="SampleData = $event"></app-sample1> -->
sample1.component.html
<input type="text" placeholder="Center Area Title" #sampleTitle (keyup)="onChange(sampleTitle.value)" />
sample1.component.ts
export class Sample1Component implements OnInit {
@Output("sampleEvent") sampleEvent = new EventEmitter();
onChange(value) {
console.log(value);
this.sampleEvent.emit(value);
}
constructor() {}
ngOnInit() {}
}
请有人在这里帮我....
解决方案
RouterOutlet
路由组件与包含( )的组件没有内在关系<router-outlet>
。很可能找到一种方法通过 路由组件从路由组件发出数据RouterOutlet
,但这不是解决此问题的规范方法。更传统的解决方案是使用外部单例(服务),其中包含用于在不具有直接继承关系的组件之间传输数据的可观察对象。
- 使用事件字段创建
@Injectable()
服务类Subject
- 将此服务添加到模块提供程序
- 将此服务注入到路由组件 (
Sample1Component
) 和容器组件 (CenterComponent
) - 监听容器组件中 observable 字段的变化 (
CenterComponent
) Sample1Component
向路由组件 ( )中的可观察主题发出更改
推荐阅读
- ionic-framework - 此处地图未显示在 Ionic 选项卡中
- svn - TortoiseSVN:错误运行上下文:“试图以访问权限禁止的方式访问套接字”
- archlinux - 怎么说 pacman 那个包已经更新了?
- authentication - 如何设置 kubeapi 服务器以允许来自集群外部的 kubectl
- java - 从 Java 中的 jTable 中选择已排序的数据
- powershell - DockerFile 的一些问题
- excel - 将文本框值与单元格值进行比较
- sql-server - 带有命名空间的 TSQL xml 输出
- javascript - 循环 for 没有得到数组的正确位置,为什么?
- bazel - 无法连接到 bazel 服务器