How to share data between components using a service properly?

前端 未结 1 1679
悲哀的现实
悲哀的现实 2020-11-27 21:22

I am learning angular2 and was able to share data between sibling components using input/output.

Here is my working example.

//our root app componen         


        
相关标签:
1条回答
  • 2020-11-27 21:57

    You can always just create a binding to a variable on a service from two different components. In this example one component increments a number and the other component displays the value

    You won't be able to detect and respond to changes with this approach. A more robust approach would be to use an observable to broadcast changes to the state in your service. e.g.

    import {BehaviorSubject} from "rxjs/BehaviorSubject"
    
    export class MyService {
        private state$ = new BehaviorSubject<any>('initialState');
    
        changeState(myChange) {
            this.state$.next(myChange);
        }
    
        getState() {
            return this.state$.asObservable();
        }
    }
    

    Then your components could subscribe to state changes and change the state by calling custom methods on the service. I have a concrete example of this approach here https://github.com/robianmcd/ng2-redux-demo/blob/redux-demo-with-service/app/user.service.ts

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