I have two sibling components, one MapComponent and one MenuComponent. Every project is displayed on a GoogleMap (MapComponent), when I click on a marker it gets the id for that project (siteId). What I want to do is to get that project id and use it in the links of my menu, so that for every project it makes a unique link with the project id, like: /project/10001 I have a shared service since sibling components can't exchange values directly. I can write the project id to the shared service but my problem is with picking up the project id in my menulinks. How do I do this? (I'm using 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>
SharedService
@Injectable()
export class SharedService {
public constructor() {
console.log('Service is succesfully initialized');
}
siteId;
selectedSite(siteId) {
this.siteId = siteId;
console.log(siteId);
}
}
Here is what I would do in your situation. Angular 2 send array another page
I recommend the service approach as you have most of your components setup towards that
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 } });
Can you not generate the links like this?
> 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>
Your service need bit of tweaking for this.
@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(); } }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.