gpt4 book ai didi

angular - 如何将数据传递给 Angular 路由组件?

转载 作者:太空狗 更新时间:2023-10-29 16:44:13 25 4
gpt4 key购买 nike

在我的一个 Angular 2 路由模板 (FirstComponent) 中,我有一个按钮

first.component.html

<div class="button" click="routeWithData()">Pass data and route</div>

我的目标是要实现:

Button click -> route to another component while preserving data and without using the other component as a directive.

这是我试过的...

第一种方法

在同一个 View 中,我正在存储基于用户交互收集的相同数据。

first.component.ts

export class FirstComponent {
constructor(private _router: Router) { }

property1: number;
property2: string;
property3: TypeXY; // this a class, not a primitive type

// here some class methods set the properties above

// DOM events
routeWithData(){
// here route
}
}

通常我会通过

路由到 SecondComponent
 this._router.navigate(['SecondComponent']);

最终将数据传递给

 this._router.navigate(['SecondComponent', {p1: this.property1, p2: property2 }]);

而带有参数的链接的定义是

@RouteConfig([
// ...
{ path: '/SecondComponent/:p1:p2', name: 'SecondComponent', component: SecondComponent}
)]

这种方法的问题是,我猜我无法在 url 中传递复杂数据(例如 object,如 property3);

第二种方法

另一种方法是将 SecondComponent 作为 指令 包含在 FirstComponent 中。

  <SecondComponent [p3]="property3"></SecondComponent>

但是我想路由到那个组件,而不是包含它!

第三种方法

我在这里看到的最可行的解决方案是使用服务(例如FirstComponentService)来

  • 存储 FirstComponent 中的 routeWithData() 数据 (_firstComponentService.storeData())
  • SecondComponent
  • 检索 ngOnInit() 中的数据 (_firstComponentService.retrieveData())

虽然这种方法看起来完全可行,但我想知道这是否是实现目标的最简单/最优雅的方法。

一般来说,我想知道我是否遗漏了其他可能的方法来在组件之间传递数据,尤其是使用尽可能少的代码

最佳答案

更新 4.0.0

参见 Angular Angular Router - Fetch data before navigating了解更多详情。

原创

使用服务是必经之路。在路由参数中,您应该只传递您希望反射(reflect)在浏览器 URL 栏中的数据。

参见 Angular Angular Cookbook Component Communication - Bidirectional Service .

RC.4附带的路由器重新引入了data

constructor(private route: ActivatedRoute) {}
const routes: RouterConfig = [
{path: '', redirectTo: '/heroes', pathMatch: 'full'},
{path: 'heroes', component: HeroDetailComponent, data: {some_data: 'some value'}}
];
class HeroDetailComponent {
ngOnInit() {
this.sub = this.route
.data
.subscribe(v => console.log(v));
}

ngOnDestroy() {
this.sub.unsubscribe();
}
}

另见 Plunker .

关于angular - 如何将数据传递给 Angular 路由组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36835123/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com