Angular 2 send data from component to service

30,508

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.

Share:
30,508
IntoTheDeep
Author by

IntoTheDeep

Like most of us, I was born. Some years later I created my first website. I love traveling and I'm an espresso snob. I share my knowledge about the web with my students in college and I would love to teach at your company. For those that are interested in old school paper, I have a bachelor degree in IT and a master degree in commercial sciences. Yup, that last one is for making sure I earn more than I spend. I love running, I even made an app for making running with others easier. If you ever feel like going for a run and talk shop, I’m cool with that.

Updated on October 26, 2020

Comments

  • IntoTheDeep
    IntoTheDeep over 3 years

    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: Array<any> = MyData;
        public constructor(private myService: MyService) {
          this.myService.data = this.data;
        }
    }
    

    and service:

    @Injectable()
    export class TablePageService {
        public data: Array<any>;
        constructor() {
            console.log(this.data);
            // undefined
        }
    }
    

    Getting data is undefined. How to make it works?

  • IntoTheDeep
    IntoTheDeep almost 7 years
    Where MyData in component2 came from?
  • SrAxi
    SrAxi almost 7 years
    I just took it from your code: public data: Array<any> = MyData;. It could also be declared as public data = {}; for example, depends on the data type you are working with. I just wanted to keep it close to your example so it's more understandable for you.
  • IntoTheDeep
    IntoTheDeep almost 7 years
    Can I set two parameters? Let say two separate strings? Do I need two subjects and two Observables?
  • SrAxi
    SrAxi almost 7 years
    Send a second parameter in the same method. w3schools.com/js/js_function_parameters.asp
  • Nad G
    Nad G over 5 years
    Hi, I find your solution pretty accurate but I'm having a trouble in the receiver component, so let me ask you a question: the data returned from the subscribe must be an Array of even objects are fine?
  • SrAxi
    SrAxi over 5 years
    @NadG Hello! Can be any type of data actually. You can send a Number, String, Object, Array...
  • Nad G
    Nad G over 5 years
    @SrAxi, snap, I was hoping that the problem is the type of the data xD Well, good to know that it can be of any type. Thank you for your answer!
  • Debo
    Debo over 5 years
    receiver component not getting the data
  • SrAxi
    SrAxi over 5 years
    BehaviorSubject is just a specialization of Subject that takes the latest value from the stream of data. The isse is probably not the type of Subject in your code, probably the issue is related to when you're subscribing.