Maxime Alza
Maxime Alza

Reputation: 85

Problem with service when sending value from one component to another

I have a service which send value from one component to another, when I click on a button.

When I'm on the child component, the first line of my code is to log the value that I have send. But, the value is logged only when I quit the page, I don't understand why ?

This is my service :

export class DataService{

  public affaireSource = new Subject();
  currentAffaire = this.affaireSource.asObservable();

  constructor(){}

  changeAffaire(affaire : number){
    this.affaireSource.next(affaire);
  }

}

This is my parent component code :

export class EncoursComponent{

  constructor(private serviceData : DataService, private router : Router) {
  }


  //Fonction qui permet de dessiner les lignes et les points
  draw(id: any, events: any, options: any) {


    svg.selectAll("circle")



      //When I click, I send the data and I'm redirected
      .on("click",(d: any) => {


        this.serviceData.changeAffaire(4)

        this.router.navigate("/affecter");


      });
  }

And this is where I'm supposed to get data :

export class AffecterComponent implements OnInit {


  constructor(private data : DataService, private route : ActivatedRoute) {

    //Here, the data need to be logged
    this.data.currentAffaire.subscribe(affaire => console.log(affaire));

  }

Instead to be logged in the line commented, I only get the value for example when I go back to the previous page, the last thing done is to log the value.

Upvotes: 0

Views: 23

Answers (1)

Robert garcia
Robert garcia

Reputation: 591

Use BehaviorSubject instead of Subject

Upvotes: 1

Related Questions