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