[英]communication between two sibling components without using service in angular2/4
[英]Shared Service between two sibling components in Angular4
我有兩個同級組件,一個MapComponent和一個MenuComponent。 每個項目都顯示在GoogleMap(MapComponent)上,當我單擊標記時,它將獲得該項目的ID(siteId)。 我想要做的就是獲取該項目ID,並在菜單的鏈接中使用它,以便對於每個項目,它都與項目ID形成唯一的鏈接,例如:/ project / 10001由於同級組件,我有一個共享服務不能直接交換價值。 我可以將項目ID寫入共享服務,但是我的問題是在菜單鏈接中選擇了項目ID。 我該怎么做呢? (我正在使用Angular4)
MapComponent
clickedMarker(siteId: string) {
this.ss.selectedSite(siteId);
this.route.navigate(['project', siteId]);
}
MenuComponent
selectedSite = this.sharedService.siteId;
<a class="submenu" *ngFor="let submenu of item.submenu, let i = index"
md-list-item [routerLink]="[submenu.url, selectedSite]">
<i class="material-icons spacer">{{submenu.icon}}</i>
<div *ngIf="!minimalMenuOpen">{{submenu.name}}</div>
</a>
共享服務
@Injectable()
export class SharedService {
public constructor() {
console.log('Service is succesfully initialized');
}
siteId;
selectedSite(siteId) {
this.siteId = siteId;
console.log(siteId);
}
}
這是我會根據您的情況采取的措施。 Angular 2發送數組另一頁
我建議您采用服務方法,因為您已將大部分組件設置為此
activePage: number; constructor(private path: ActivatedRoute) {} ngOnInit() { this.path.queryParams.subscribe(path => { // If there is a value this.activePage = +path["id"]; if (isUndefined(this.activePage)) { // What if there is no value } });
您不能生成這樣的鏈接嗎?
> MenuComponent TS file selectedSite; this.sharedService.getSelectedSiteId().subscribe( (siteId: any) => { this.selectedSite = siteId; });
> MenuComponent HTML file <!-- This make sure links don't start creating till selectedSite available --> <ng-container *ngIf="!selectedSite"> <a class="submenu" *ngFor="let submenu of item.submenu, let i = index" md-list-item [routerLink]="[submenu.url]" [queryParams]="{id:'"+ selectedSite + "'}"> <i class="material-icons spacer">{{submenu.icon}}</i> <div *ngIf="!minimalMenuOpen">{{submenu.name}}</div> </a> </ng-container>
您的服務需要對此進行一些調整。
@Injectable() export class SharedService { public constructor() { console.log('Service is succesfully initialized'); } private siteId: BehaviorSubject<any> = new BehaviorSubject(null); selectedSite(siteId) { this.siteId.next(siteId); console.log(siteId); } getSelectedSiteId(): Observable<any> { return this.siteId.asObservable(); } }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.