首页 > 解决方案 > 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() {}
}

请有人在这里帮我....

标签: angular

解决方案


RouterOutlet路由组件与包含( )的组件没有内在关系<router-outlet>。很可能找到一种方法通过 路由组件从路由组件发出数据RouterOutlet,但这不是解决此问题的规范方法。更传统的解决方案是使用外部单例(服务),其中包含用于在不具有直接继承关系的组件之间传输数据的可观察对象。

  1. 使用事件字段创建@Injectable()服务类Subject
  2. 将此服务添加到模块提供程序
  3. 将此服务注入到路由组件 ( Sample1Component) 和容器组件 ( CenterComponent)
  4. 监听容器组件中 observable 字段的变化 ( CenterComponent)
  5. Sample1Component向路由组件 ( )中的可观察主题发出更改

推荐阅读