0

Hi I am trying to pass a object from Component A to another sibling Component B and I am using service to do so and I am using Subject. But when calling the get method from service I am not able to get the data in Component B. I don't know what I am doing wrong. Any help would be great. My code is as below -

Hierarchy Service

import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import { Subject } from 'rxjs/Subject';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/map';

@Injectable()
export class HierarchyService {

  private dataObj = new Subject;
  getDataObj = this.dataObj.asObservable();

  constructor () {}

  setData(setData:Object){
    console.log("setData +++ ", setData);
    this.dataObj.next(setData);
  }
}

Component A Inside a event handler I am setting below code -

this.hierarchyService.setData(treeModel);

Component B inside ngOnInit I am trying to get the data that I set in Component A

 this.hierarchyService.getDataObj.subscribe(data => console.log("data ", data));

2 Answers 2

2

I found the solution, I was actually injecting the hierarchy service as provider for Component A and Component B. Instead I just added the service as provider for my app.module and removed as providers from Component A and Component B and it worked.

Sign up to request clarification or add additional context in comments.

Comments

1

How are you using your services is not very clear.

Are you using providers: [] on both component? in that case the both uses different instantiation and are not singleton, so data cannot be shared.

Put your service in providers array in app.module and try again.

If you want to use the @Input() @Output() to share the data then see this post Angular component communication by using Input Output decorator

1 Comment

Thanks Ali, Yes initially I was adding my service in providers for both the component that's why I was not able to get data as each component was creating singleton instance. Then I removed it and just added it to the app.module and it worked fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.