Shikha thakur
Shikha thakur

Reputation: 1289

set and get data from service angular 5

I am using angular 5 my scenario is from one component im setting the data in service and from another component i'm getting that data|

Component- 1:

makeUser(row){
  this.agentsService.setSelectedAgentData(row); // setting the data (row) in agentsService.
  const mrf =  this.modalService.open(MakeUserComponent);    
}

Service: declaring the varible in class.

public selectedData:any = {};

setter and getter methods are as below

  setSelectedAgentData(selectedTableRowData){
    this.selectedData = selectedTableRowData;
  }
  getSelectedAgentData(){
    return this.selectedData;
  }

Component - 2:

  ngOnInit() {
    this.userDetails = this.agentsService.getSelectedAgentData();
    this.roles = this.agentsService.getRolesList();
  }

Here the selectedData value is an empty object when I call the method this.agentsService.getSelectedAgentData() from component -2

Any help would be appreciated.

Upvotes: 1

Views: 8987

Answers (1)

Yaroslav Chapelskyi
Yaroslav Chapelskyi

Reputation: 210

You can use Subject (rxjs library) for this purpose. So Subject can generate data on the one hand. And on the other hand, you can subscribe to changes in any place. You service would look like this:

@Injectable()
export class YourService {

  public selectedData: Subject<any>;

  constructor() {
    this.selectedData = new Subject();
  }

  generateSelectedAgentData(row: string) {
    this.selectedData.next(row);
  }
}

In your first Component:

makeUser(row){
  this.agentsService.generateSelectedAgentData(row);
  const mrf =  this.modalService.open(MakeUserComponent);    
}

In your second Component:

constructor(private ys: YourService){
  this.ys.selectedData.subscribe(
      data => {
        console.log(data);
        this.userDetails = data;
    });
}

Upvotes: 2

Related Questions