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