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

时间:2018-01-10 12:28:14

标签: typescript angular2-directives

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

.activity-snippets {
  display: flex;
}

.activity-post-link {
  height: 215px;
  width: 33.33333333%;
}
.activity-post-link img{
  width: 100%;
  height: 100%;
  object-fit: cover;
}

这是我的login.component.ts

<div class="activity-snippets">
  <div class="activity-post-link">
    <img src="https://cdn.dribbble.com/users/476251/screenshots/2619255/attachments/523315/placeholder.png">
  </div>
  <div class="activity-post-link">
    <img src="https://cdn.dribbble.com/users/476251/screenshots/2619255/attachments/523315/placeholder.png">
  </div>
  <div class="activity-post-link">
    <img src="https://cdn.dribbble.com/users/476251/screenshots/2619255/attachments/523315/placeholder.png">
  </div>
</div>

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

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

有人可以帮我修复此错误。任何帮助,将不胜感激。谢谢

1 个答案:

答案 0 :(得分:1)

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

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

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

话虽如此,您还可以做的是设置路由器,并通过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

  

(注意:有一百万种方法可以传递一个参数&#34;但这一切都是   取决于你希望如何完成。也许它是一个公共参数,   并且您希望用户能够看到它,也许它是a的哈希值   密码,你想继续留在引擎盖下   信息,编辑你的帖子,并准确地解释一下   你想要的是什么)