Angular4:如何通过路由器添加的子节点将数据从父节点传递给子节点

Rel*_*elm 8 typescript angular

继续这个问题Angular 4 ^:如何让一个组件的多个子组件与每个子组件定位其自己的路由器插座,我可以将一些子组件注入多个父组件,现在我想从那些组件中传递数据父母,异步,对孩子.试过@Input,似乎无法获胜.

儿童

export class UserheaderComponent implements OnInit, AfterViewInit, OnChanges {
  loading;
  @Input() data;
  user = {
    name: '______________',
    icon: '',
    username: '_________',
    uid: '________'
  };
  constructor(private router: Router) {
  }

  goToUser(uid) {
    this.router.navigate(['user'], { queryParams: { uid: uid } });
  }

  ngOnInit() {
    this.user = this.data;
    console.log(this.data);
  }

  ngAfterViewInit() {
    console.log(this.data);
  }

  ngOnChanges(changes: SimpleChanges) {
    console.log(changes);
  }
}
Run Code Online (Sandbox Code Playgroud)

家长Html

  <router-outlet name='userprofile-userhead' [data]="currentUser"></router-outlet>
Run Code Online (Sandbox Code Playgroud)

家长TS

export class UserprofileComponent {
  public currentUser;

  constructor(
    private userFactory: UserFactory,
    private router: Router,
    private snack: MatSnackBar) {
    this.userFactory.checkSession(exists => {
      if (!exists) {
        return;
      }
      this.userFactory.getSessionUser((uid, user) => {
        this.currentUser = user;
      });
    });
  }
}
Run Code Online (Sandbox Code Playgroud)

和路由

path: '', component: UserprofileComponent, outlet: 'userprofile', children: [
          { path: '', component: UserheaderComponent, outlet: 'userprofile-userhead' },
        ]
Run Code Online (Sandbox Code Playgroud)

什么都没有传递给孩子,这种安排是否可能,或者我错过了什么?

无法使用共享服务.

每个组件都应该使用它自己的Id.想象一下,这是一个像上下文这样的帖子的时间轴,比如社交媒体时间轴,这是帖子的头,你知道,用户图标,名称......用户名是.因此,'post'组件会将其作为子项注入,将其传递给用户object:{name:'...',username:'...'},因此我不会看到服务将如何在此处执行.

现在,当我们在应用程序的某个地方,一个配置文件组件,搜索组件可能会调用此...

如果你仍然认为服务会做,请详细说明.

Ste*_*fan 1

我认为在这种情况下,一个有效的选择是向 UserheaderComponent 的路由添加一些参数,然后在组件初始化时获取它并从服务获取预期数据。

首先,您需要将其添加到组件的路由路径中

path: 'userHead/:userId' 
Run Code Online (Sandbox Code Playgroud)

然后,当您重定向到该参数时,您需要设置此参数,然后当组件初始化时,您可以获得此参数

this.activatedRoute.params.subscribe((params) => { const userHead= 
params['userId']; }
Run Code Online (Sandbox Code Playgroud)

最后根据该参数您可以获得预期的数据形式服务。

如果您有一个孩子,请考虑直接使用组件

<userprofile-userhead name='userprofile-userhead' [data]="currentUser"> 
</userprofile-userhead>
Run Code Online (Sandbox Code Playgroud)

而不是路由器插座。