[英]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.