How can I detect service variable change when updated from another component?

后端 未结 2 1608
伪装坚强ぢ
伪装坚强ぢ 2020-12-07 14:12

I\'m trying to get the updated value from a service variable (isSidebarVisible) which is keeps on updated by another component (header) with a clic

2条回答
  •  鱼传尺愫
    2020-12-07 14:33

    Move subscription to the service, and both components can access this value. If you need value only once, you can use it directly (like I did in sidebar.component); If you need to update something with this value it you can use getter (example in header.component).

    sidebar.service.ts:

    @Injectable() 
    export class SidebarService {
        isSidebarVisible: boolean;
    
        sidebarVisibilityChange: Subject = new Subject();
    
        constructor()  {
            this.sidebarVisibilityChange.subscribe((value) => {
                this.isSidebarVisible = value
            });
        }
    
        toggleSidebarVisibility() {
            this.sidebarVisibilityChange.next(!this.isSidebarVisible);
        }
    }
    

    sidebar.component.ts

    export class SidebarComponent {
        asideVisible: boolean;
    
        constructor(private sidebarService: SidebarService) {
            this.asideVisible = sidebarService.isSidebarVisible;
        }
    }
    

    header.component.ts

    export class HeaderComponent {
        constructor(private sidebarService: SidebarService) { }
    
        get isSidebarVisible(): boolean {
            return this.sidebarService.isSidebarVisible;
        }
    
        toggleSidebar() {
            this.sidebarService.toggleSidebarVisibility()
        }
    }
    

    You can also subscribe to the subject in either/both components and get the value there:

    this.sidebarService.sidebarVisibilityChange.subscribe(value => {...});
    

    If you want to know more about Subjects take a look here.

提交回复
热议问题