如何在其他组件中显示单击的用户个人资料数据? [英] How to display clicked user profile data in a different component?

查看:52
本文介绍了如何在其他组件中显示单击的用户个人资料数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对angular还是很陌生,并且正在尝试创建一个利用动态路由的小应用程序.我有一个成员"页面,其中列出了所有当前成员,如果您单击一个特定成员,则会加载另一个用于显示用户详细信息的页面.目前,我只是想显示您已经点击了xxxs个人资料",但是我在解决如何显示所点击的用户名时遇到了麻烦.

I am quite new to angular and am trying to create a little app that utilises dynamic routing. I have a "members" page that lists all current members whereby if you click on one specific member you load another page used for displaying the user detail. Currently I am just trying to display "You have clicked on xxxs profile" but I am having trouble working out how to get the clicked user name displayed..

成员组件:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Params, Router } from '@angular/router';

@Component({
  selector: 'app-members',
  template: `
    <li *ngFor='let members of members' (click)='onSelect(members)'>
      <span class='badge'>  {{members.name}} : {{members.id}}  </span>
    </li>
  `  ,
  styleUrls: ['./members.component.css']
})
export class MembersComponent implements OnInit {

  members = [
    {'id': 1, 'name': 'Person 1'},
    {'id': 2, 'name': 'Person 2'},
    {'id': 3, 'name': 'Person 3'}
  ];

  constructor(private router: Router) { }

  ngOnInit() {
  }

  onSelect(members) {
    this.router.navigate(['/member', members.id]);
  }

}

我不知道应该如何在成员组件内部显示单击的个人资料名称,有人愿意为我提供解决方案吗?

I am at a loss as to how I should go about displaying the clicked profile name inside of the member component, anyone care to suggest a solution to me?

成员组件:

 import { Component, OnInit } from '@angular/core';
 import { ActivatedRoute, Params, ParamMap, Router } from '@angular/router';

 import { MembersComponent } from '../members.component';

@Component({
   selector: 'app-member',
  template: `
    You have clicked on {{  ****to be displayed****  }} profile!
   `,
  styleUrls: ['./member.component.css']
})

export class MemberComponent implements OnInit {
  constructor(private router: ActivatedRoute ) { }

  ngOnInit() {
  }
}

推荐答案

与上述解决方案一起,如果您不介意URL中的名称,则可以在查询参数中传递名称.

Along with the above solution, you can pass the name in query params, if you don't mind the name in the URL..

在成员下部分:

onSelect(members) {
    this.router.navigate(['/member', members.id], {queryParams: {name: members.id}});
}

在成员"组件下:

...
template: `You have clicked on {{memberName}} profile!`,
...

public memberName: string = "";
public subs$;
constructor(private _route: ActivatedRoute) ...

ngOnInit() {
    this.subs$ = this._route
        .queryParams
        .subscribe((params) => {
            this.memberName = params["name"];
        })
}

// this is to kill the subscription
ngOnDestroy() {
    if (this.subs$) {
        this.subs$.unsubscribe();
    }
}

这篇关于如何在其他组件中显示单击的用户个人资料数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆