簡體   English   中英

訪問Angular中其他組件的變量

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM