无法在angular2中的组件之间共享数据

unable to share data between components in angular2

您好,我正在开发 angular2 应用程序。我正在尝试在组件之间共享数据。这是我的 app.component.ts

 @ViewChild(ChildComponent) child;
 message: string;
 ngAfterViewInit() {
 alert(this.message = this.child.message);}

这是我的login.component.ts

message: string = "Hola Mundo!";

每当我的应用程序加载时,我都会遇到以下错误。

RROR TypeError: Cannot set property 'message' of undefined
    at AppComponent.ngAfterViewInit (app.component.ts:88)

谁能帮我解决这个错误。任何帮助,将不胜感激。谢谢

要在父组件和子组件之间共享,我所做的是在 html 中传递 via 参数。像这样:

<app-child [parameterName]="value"></app-child>

我也做的是有一个服务保存我所有的视图将要使用的相关数据,并使用该服务而不是过去的视图。


话虽如此,你也可以设置一个Router,通过get传参

this.router.navigate(['home/:id']);

然后在另一个组件中你应该这样得到它

this.route.paramMap
.switchMap((params: ParamMap) =>
  console.log(params.get('id')); //prints the id

我把这个留给你,非常有用,我几乎完全从那里得到了我的答案

https://angular.io/guide/router

(Note: there are a million ways to "pass a parameter" but it all depends in how you want it to be done. Maybe it's a public parameter, and you want the user to be able to see it, maybe it's the hash of a password and you want to remain under the hood, for further information, edit your post, and explain a little better, precisely what you want)