Search code examples
javascriptangulartypescriptangularjs-scope

Angular2 Service's field issue


I have a service:

@Injectable()
export class MyService implements IMyService {
   myServiceArray: Array<string> = ["hi", "hello", "yoyo"];
}

This Service is injected in a Component that updates the array of string with ngModel. When I try to print the array from the Component or from the Service everything is working fine (aka the array is updated with the ngModel).

I also @Inject such Service in another 1.

@Injectable()
export class AnotherService implements IAnotherService {

  constructor(public myService: MyService) {
  }

  printValues() {
     console.log(this.myService.myServiceArray);
  }
}

When I call printValues(), ["hi", "hello", "yoyo"] is printed even if I updated the values of the array with a model!

What am I doing wrong?

EDIT:

The code of the component is the following.

@Component({
  selector: 'app-root',
  providers: [MyService],
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppCustomerData implements IAppCustomerData {

  constructor(public myService: MyService) {
  }
}

Solution

  • You have to look that you inject the same instance of the service, if you have multiple instances of the service each one has a own array in it.

    I would try to use the local storage to store the data in the service, than you can have multiple instances and each one can edit or return the same value: How to store token in Local or Session Storage in Angular 2?

    Maybe this answers your problem: How do I create a singleton service in Angular 2?