Question: Create unique instance of provider ionic 3


Create unique instance of provider ionic 3

Answers 1
Added at 2017-11-30 18:11

I am creating an Ionic app. I have 3 providers - database provider, portfolio provider and user provider. All 3 are Injectable. I have created it this way because several other pages need to use their function calls (i.e. they should not share the same data, they all should create new instances)

Both the portfolio and user provider import the database provider, as the need to make the same database calls to retrieve data.

I have 1 page - ViewPortfolio. The ViewPortfolio page imports the user provider (to know who the user is) and portfolio provider (to get the users portfolio data). For some reason, these 2 providers seem to be sharing the same instance for database provider. This is how I use them:


import { DatabaseProvider } from '../providers/database-provider';

  providers: [DatabaseProvider]
export class PortfolioProvider {
    public portfolio_list: any = new BehaviorSubject<Array<string>>([]);

    constructor(private dbProvider: DatabaseProvider) {
        this.dbProvider.enableDataListener(this.protfolio_path); // set path
        this.dbProvider.db_listener.subscribe(value => {  // subscribe to data in the path
            // do stuff

The user portfolio is the same, the only difference is the path its listening to is different.

However, when I change data in the portfolio path, the subscribe call is also triggered in the user path (and vice versa). Thus, even though I added DatabaseProvider in the components providers, its not creating unique instances. Why is this?

I figured it might be because I am importing them both on the same page but I am not convinced that's why it is not working. How do I make the 2 providers use unique instances on databaseprovider, while calling them both on the same page?

This is what my app.moudle.ts file looks like (please note that DatabaseProvider is not included in my app.module.ts file)

// ... more imports
import { PortfolioProvider } from '../providers/portfolio-provider';
import { UserProvider } from '../providers/user-provider';
  declarations: [
    // ... more
  imports: [
    // ... more
    IonicModule.forRoot(MyApp, {
        backButtonText: '',
        tabsPlacement: 'bottom'
  bootstrap: [IonicApp],
  entryComponents: [
    // ... more
  providers: [
    // ... more
export class AppModule {}


Answers to

Create unique instance of provider ionic 3

nr: #1 dodano: 2017-12-01 00:12

Did you remove the provider from app.module.ts (root AppModule)?

From the Angular Documentation:

Scenario: service isolation
While you could provide VillainsService in the root AppModule (that's where you'll find the HeroesService), that would make the VillainsService available everywhere in the application, including the Hero workflows.

If you generated the provider using ionic-cli, it'll automatically add it to the root AppModule.

Source Show
◀ Wstecz