0

i have the same problem of this issue :

Share data between components using a service in Angular2

but it won't work because i think injecting service into two components mean that there is two instance ot the service class . so trying to modify the data from component in the service and see the change in the other component still not working . what is the solution so ?

NB :

i have try the solutions in the comments but still not working ...

this is my service :

import { Injectable } from '@angular/core';

@Injectable()
export class TestService {

   counter: number = 0 ;
  constructor() {
    console.log('instanciate Test Service' + this.counter ) ;
    this.counter ++ ;

  }

   setCounter(counter: number){
    this.counter =counter ;
    console.log('new value of counter is ' + this.counter );
  }


}

the first component :

@Component({
  selector: 'rb-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit , OnChanges ,DoCheck{
  bindingdata = 'test' ;
  data: number;


  constructor(public  _ts: TestService) {

  }
   ngOnChanges(){
    this.data=this._ts.counter ;
    console.log('is changing');
   }
   ngDoCheck(){
     this.data=this._ts.counter ;

     console.log('is doing check');

   }
  ngOnInit() {
    this.data = this._ts.counter;
        }
}

template of the first component :

{{data}}
<input type="text" [(ngModel)]="bindingdata" />

the second component :

@Component({
  selector: 'rb-other-test',
  templateUrl: './other-test.component.html',
  styleUrls: ['./other-test.component.css']
})
export class OtherTestComponent implements OnInit ,OnDestroy{
  data: number;
  constructor(public _ts: TestService) { }

  ngOnInit() {
   this.data= this._ts.counter;
  }

  public  change(){
    this._ts.setCounter(7878);
    this.data = this._ts.counter;
  }

  ngOnDestroy() {
  }

}

the template of second component :

<input type="submit" value="change" (click)="change()">

{{data}}

result :

enter image description here

Yassine CHABLI
  • 3,459
  • 2
  • 23
  • 43

0 Answers0