Shared service in other provider


#1

Hey,

I created a shared service to use in all my components/pages.
In this service I do things like testing the network connection etc.
Now I would like to access this functionality in another “regular” provider. For example to test the network to decide where to get my data from.
Basically it works fine, but it creates a new instance of the service instead of using the global one like the components do.

This is how my shared service looks like:

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

@Injectable()
export class SharedService {
  public hasNetworkConnection : boolean;

  constructor() {  }

  hasNetwork() : boolean {
     /* ... */
  }
}

And my other provider looks like this:

import { Injectable } from '@angular/core';
import { SharedService } from './sharedservice';

@Injectable()
export class ExampleProvider {
  constructor( private sharedService: SharedService ) {  }

  getData() {
   this.sharedService.hasNetwork();
  }
}

Is it even possible to use it in another provider?
Or is there any workaround for this?


#2

hi, i am struggling with the same issue :confused:


#3

This stackoverflow question from september seems to be about the same:

unfortunately it has not been answered as well :unamused:


#4

Solved!

Ok I went over to just try different thing coming to my mind and luckily found what seems to be the cause of the problem :smiley:

In my app.components.ts I had my SharedService added to the providers (like in every tutorial):

@Component({
  templateUrl: 'app.html',
  providers: [SharedService]
})

Now I just removed the SharedService from the providers and it stopped creating a new Instance when it’s called inside another provider.
Sometimes you just have to get lucky :wink:


#5