繁体   English   中英

访问Angular中其他组件的变量

[英]Access variables of other components in Angular

我正在使用TypeScript在Angular中开发一个应用程序:

我的app.component在顶部具有导航,然后在其他组件的路由出口

<navigation></navigation>
<router-outlet></router-outlet>

导航

@Component({
  selector: 'navigation',
  directives: [ROUTER_DIRECTIVES],
  template: `{{ HERE SHOULD BE USERNAME }}    <a [routerLink]="['Home']">Home</a> | <a [routerLink]="['Logout']">Logout</a>`
})
export class NavigationComponent {}

登录(加载到路由器出口内)

@Component({
    selector: 'login-component',
    templateUrl: 'app/components/login/login.html',
})
export class LoginComponent {

  username ;

  constructor(public router: Router, public http: Http) {
  }
...
}

login.component管理登录过程。 用户登录后->我想在Navigation.component显示其用户名。 如何将用户名从login.component传递给Navigation.component 或者如何从Navigation.component访问login.component内部的变量username

使它们都使用通用服务,并将用户名存储在服务中。

登录组件将用户名存储在服务中:

userService.setUser(theUser);

导航组件允许从服务中获取用户:

getUser() {
    return userService.getUser();
}

导航组件的视图使用

{{ getUser() }}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM