Angular4中两个兄弟组件之间的共享服务

时间:2017-09-28 12:29:27

标签: angular service components shared

我有两个兄弟组件,一个MapComponent和一个MenuComponent。每个项目都显示在GoogleMap(MapComponent)上,当我点击标记时,它会获得该项目的id(siteId)。我想要做的是获取该项目ID并在我的菜单链接中使用它,以便每个项目都与项目ID建立一个唯一的链接,如:/ project / 10001 我有一个共享服务,因为兄弟组件不能直接交换值。我可以将项目ID写入共享服务,但我的问题是在我的menulinks中获取项目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>

SharedService

@Injectable()
export class SharedService {

  public constructor() {
    console.log('Service is succesfully initialized');
  }

  siteId;
  selectedSite(siteId) {
    this.siteId = siteId;
    console.log(siteId);
  }

}

1 个答案:

答案 0 :(得分:0)

以下是我在你的情况下会做的事情。 Angular 2 send array another page

我推荐使用服务方法,因为您已将大部分组件设置为

&#13;
&#13;
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
      }
    });
&#13;
&#13;
&#13;

你能否生成这样的链接?

&#13;
&#13;
> MenuComponent TS file

selectedSite;
this.sharedService.getSelectedSiteId().subscribe(
  (siteId: any) => {
    this.selectedSite = siteId;
  });
&#13;
> 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>
&#13;
&#13;
&#13;

您的服务需要对此进行一些调整。

&#13;
&#13;
@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();
  }

}
&#13;
&#13;
&#13;