[英]Angular2 pass data from component to root component, without child component
我有根組件,它包含路由,還附加了一些組件:
路由器:
const appRoutes: Routes = [
{
path: 'welcome',
component: BaseComponent
},
{
path: '',
redirectTo: '/welcome',
pathMatch: 'full'
},
{
path: 'story/:id',
component: DetailComponent
},
{
path: 'about-me',
component: AboutComponent
},
{
path: ':url/:id',
component: CategoryComponent
},
{
path: 'authentication',
component: DashboardComponent
}
]
export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);
根html:
<header *ngIf="!x">
<h1><a routerLink="/">{{title}}</a></h1>
<nav>
<a *ngFor="let nav of navigation" routerLink="{{ nav.url }}/{{ nav.category }}">{{ nav.title }}</a>
<a routerLink="/about-me">about-me</a>
<a *ngIf="logged" routerLink="/authentication">dashboard</a>
</nav>
</header>
<router-outlet></router-outlet>
<social></social>
當我進入DashboardComponent時,我希望向RootComponent發送一些變量或事件,並在RootComponent的視圖內隱藏一個元素(ngIf="!x")
。 請提供提示或建議。
雷加斯烏蘭德
您可以使用服務在組件之間傳遞數據。
服務語法:
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
@Injectable()
export class ProductSearchService{
private pageNumberChangedSource = new Subject<any>();
pageNumberChanged$ = this.pageNumberChangedSource.asObservable();
changePage(param: any){
this.pageNumberChangedSource.next(param);
}
}
發送數據的組件:
export class ProductManagerComponent {
constructor(private pagerService: PagerService){}
pageChanged(pagenum)
{
this.productSearchService.changePage(pageNum)
}
}
接收器組件:
export class ProductSearchComponent {
constructor(private productSearchService: ProductSearchService) {
this.productSearchService.pageNumberChanged$.subscribe(param => {
this.getPageFromSearchResult(param);
})
}
}
更詳細的教程在這里
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.