简体   繁体   中英

Access variables of other components in Angular

I am developing an app in Angular using TypeScript:

My app.component has a navigation on the top, and then router-outlet of other components

<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. After the user is logged in -> I'd like to display its user-name in Navigation.component . How could I pass the User-Name to Navigation.component from login.component ? Or how to access a variable username inside login.component from Navigation.component ?

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() }}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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