简体   繁体   English

访问Angular中其他组件的变量

[英]Access variables of other components in Angular

I am developing an app in Angular using TypeScript: 我正在使用TypeScript在Angular中开发一个应用程序:

My app.component has a navigation on the top, and then router-outlet of other components 我的app.component在顶部具有导航,然后在其他组件的路由出口

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

Navigation 导航

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

Login (loaded inside router-outlet) 登录(加载到路由器出口内)

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

  username ;

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

The login.component manages the login procedure. login.component管理登录过程。 After the user is logged in -> I'd like to display its user-name in Navigation.component . 用户登录后->我想在Navigation.component显示其用户名。 How could I pass the User-Name to Navigation.component from login.component ? 如何将用户名从login.component传递给Navigation.component Or how to access a variable username inside login.component from Navigation.component ? 或者如何从Navigation.component访问login.component内部的变量username

Make them both use a common service, and store the username in the service. 使它们都使用通用服务,并将用户名存储在服务中。

The login component stores the username in the service: 登录组件将用户名存储在服务中:

userService.setUser(theUser);

The navigation component allows getting the user from the service: 导航组件允许从服务中获取用户:

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

The view of the navigation component uses 导航组件的视图使用

{{ getUser() }}

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

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