【问题标题】:Cross component communication in angular角度的跨组件通信
【发布时间】:2019-05-18 13:06:15
【问题描述】:

我的应用中有三个组件。第一个header 组件,第二个sideNavBar 组件和第三个overview 组件。 我在下面的图片中显示了 1,2,3。

当我选择任何社交平台时,我会将用户发送到home/overview,我希望在我的sideNavBar 中,相关图标的颜色发生变化。

当用户点击每个社交标题时我使用的方法在这里:

onActiveSocial(social) {
    localStorage.setItem('activeAccountMedium', social);
    this.appGlobal.activeSocial = social;
    this.router.navigate(['home/overview']);
  }

我知道我必须在这个方法中写一些触发器来使sideNavBar中的图标改变颜色。

我必须说这三个组件彼此无关。

我该怎么做?

【问题讨论】:

  • 您使用localStorage 保存当前标签,对吗?
  • 您可以使用routerLinkActiveangular.io/api/router/RouterLinkActive
  • @SangwinGawande 是的,我使用 localStorage 随时了解哪个社交平台处于活跃状态。
  • 您为此尝试过 SharedService 吗?
  • @SangwinGawande 是的,但我认为我做错了,因为它不起作用

标签: angular components


【解决方案1】:

解决方案1:(如果你想在sidenav上应用的颜色与活动路由无关) 服务是为相同而设计的,(依赖注入)

export class SomeService {
private color: BehaviorSubject<string> = new BehaviorSubject<string>('Green');
get _color() {
  return this.color.asObservable();
}
constructor() {}

public updateColor(val) {
 this.color.next(val);
 }
}

在组件的父模块或根模块(app.module.ts)中提供此服务

在组件中注入服务

    overview.component.ts
    constructor(private someService: SomeService) {

    }
    // update the variable here on some method
    this.someService.updateColor('red');

    sidenav.component.ts
    color: string;
    constructor(private someService: SomeService) {}
    ngOnInIt() {
      this.someService._color.subscribe((val) => {
         this.color= val;
      });
    }
   ngOnDestroy() {
   //unsubscribe on destroye
  }

说实话,这种问题的 overKilling 只需使用 routerLinkActive 会更容易

2.解决方案2: 您可以使用 Angular 提供的 routerLinkActive 属性在路由处于活动状态时应用类 https://angular.io/api/router/RouterLinkActive 了解更多

【讨论】:

  • 如何使用 get 和 set 方法来更新我的侧导航组件。当我的主应用程序出现时,侧导航和标题,执行。当我点击标题上的社交按钮时,我的 sidenav 组件不会再次执行,所以什么都不会更新
猜你喜欢
  • 1970-01-01
  • 2021-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-30
  • 2010-09-16
  • 1970-01-01
相关资源
最近更新 更多