Angular 2 send data from component to service

前端 未结 2 677
臣服心动
臣服心动 2020-12-16 18:01

My target is to send data from Angular component to service and use service methods to work on it. Example:

export class SomeComponent {
    public data: Arr         


        
相关标签:
2条回答
  • 2020-12-16 18:57

    An example if interaction between service and component could be:

    Service:

    @Injectable()
    export class MyService {
        myMethod$: Observable<any>;
        private myMethodSubject = new Subject<any>();
    
        constructor() {
            this.myMethod$ = this.myMethodSubject.asObservable();
        }
    
        myMethod(data) {
            console.log(data); // I have data! Let's return it so subscribers can use it!
            // we can do stuff with data if we want
            this.myMethodSubject.next(data);
        }
    }
    

    Component1 (sender):

    export class SomeComponent {
        public data: Array<any> = MyData;
    
        public constructor(private myService: MyService) {
            this.myService.myMethod(this.data);
        }
    }
    

    Component2 (receiver):

    export class SomeComponent2 {
        public data: Array<any> = MyData;
    
        public constructor(private myService: MyService) {
            this.myService.myMethod$.subscribe((data) => {
                    this.data = data; // And he have data here too!
                }
            );
        }
    }
    

    Explanation:

    MyService is managing the data. You can still do stuff with data if you want, but is better to leave that to Component2.

    Basically MyService receives data from Component1 and sends it to whoever is subscribed to the method myMethod().

    Component1 is sending data to the MyService and that's all he does. Component2 is subscribed to the myMethod() so each time myMethod() get called, Component2 will listen and get whatever myMethod() is returning.

    0 讨论(0)
  • 2020-12-16 19:02

    There is a small issue with the receiver component in @SrAxi s reply as it can't subscribe to the service data. Consider using BehaviorSubject instead of Subject. It worked for me!

    private myMethodSubject = new BehaviorSubject<any>("");
    
    0 讨论(0)
提交回复
热议问题