Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 send data from component to service

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?

like image 925
IntoTheDeep Avatar asked May 19 '17 09:05

IntoTheDeep


People also ask

How do you pass data from one component to another through service?

If you want to pass data from the child component to the parent component use @Output() and EventEmitter. To pass data from the child to the parent, you have to emit it from the child. The parent will be listening for the event will grab the data.

Can we send data from one component to another in Angular?

When we build components in an application, we maybe need to share or send data from parent to child or without a direct connection. Angular provides different these ways to communicate components: Using Input() and Output() decorators. Using Viewchild decorator.


1 Answers

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.

like image 200
SrAxi Avatar answered Oct 23 '22 06:10

SrAxi