Angular 2 send data from component to service

Viewed 34052

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?

2 Answers

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>("");
Related