How to set or pass a property state between unnested component in Angular

前端 未结 1 454
陌清茗
陌清茗 2020-12-22 13:16

I develop a web application with tech Angular. But now I am having a problem, how can I pass or set a property from a compoennt to the other component, which are not parent-

相关标签:
1条回答
  • 2020-12-22 13:54

    To share data between two components that don't have a parent child relationship you would use a service like you explained. It hard to tell what the issue is without seeing your MessageService implementation.

    I did throw together a simple example that you can review and apply to your situation. Linked below are a few resources to help explain Angular component interaction and a stackblitz with an example where I created a LoadingService similar to how you could create a MessageService, something similar to this...

    import { Injectable } from '@angular/core';
    import { Observable } from 'rxjs/Observable';
    import { BehaviorSubject } from 'rxjs/BehaviorSubject';
    
    @Injectable()
    export class LoadingService {
    
      private isLoadingSource: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
      public isLoading: Observable<boolean> = this.isLoadingSource.asObservable();
    
      constructor() { }
    
      set loading(value: boolean) {
        this.isLoadingSource.next(value);
      }
      
    }
    

    Resources

    https://stackblitz.com/edit/angular-gjpsgi

    https://angular.io/guide/component-interaction

    https://angularfirebase.com/lessons/sharing-data-between-angular-components-four-methods/

    0 讨论(0)
提交回复
热议问题