0

I have a ShareService in angular 2,

******************************shareService*************************
import { BehaviorSubject , Subject}    from 'rxjs/Rx';
import { Injectable } from '@angular/core';


@Injectable()
export class shareService {


    isLogin$:BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
    CheckUser = this.isLogin$.asObservable();
    public isLogin (bool){
        this.isLogin$.next(bool);
    }
}

and its my another component and subscibe the CheckUser;

***********************another Component*******************************

        _shareService.CheckUser.subscribe((val) =>{
            *********all of this scope execute for several times just i have one another component and one next function*******
            this.isLogin = val;
            alert(val);
            if(this.isLogin){

                console.log("req req req");
                this.MyBasket();

            }
            else if(this.ext.CheckLocalStorage("ShopItems")){

                    this.ShopItems = JSON.parse(localStorage.getItem("ShopItems"));
                    setTimeout(() => {
                        _shareService.sendShopItems(this.ShopItems);
                    },100);

            }

        });

my problem is i execute once this.isLogin$.next(bool) but subscribe function execute twice or several times !!!! my basket function is an xhr request this means when user loged in i get the several request to server!!!i cant fix it...i dont know this problem is for angular 2 or not,Anyone have this problem?? last a few days i Involved in this problem!

  • Same as in http://stackoverflow.com/questions/37654458/shareservice-in-angular-2-twice-subscribe-the-next-function. Please provide a Plunker to reproduce. – Günter Zöchbauer Jun 07 '16 at 08:19

2 Answers2

0

The problem is that your shareService is getting multiple instances.

One of the solutions is forcing the service to be a singleton.

Something like this should work:

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

@Injectable()
export class shareService {
  private static instance: shareService = null;

  // Return the instance of the service
  public static getInstance(/*Constructor args*/): shareService {
    if (shareService.instance === null) {
       shareService.instance = new shareService(/*Constructor args*/);
    }
    return shareService.instance;
  }

  constructor(/*Constructor args*/) {}
}

export const SHARE_SERVICE_PROVIDER = [
  provide(shareService, {
    deps: [/*Constructor args dependencies*/],
    useFactory: (/*Constructor args*/): shareService => {
      return shareService.getInstance(/*Constructor args*/);
    }
  })
];

Everything that is required on your current constructor should be placed where it says constructor args

Now on your components you use the service like this:

@Component({
  providers: [SHARE_SERVICE_PROVIDER]
})

And then you can call it like you usually do.

Another solution would be injecting your current service on the main component of the app. See here for more info.

Community
  • 1
  • 1
Joel Almeida
  • 7,939
  • 5
  • 25
  • 51
  • i import import {SHARE_SERVICE_PROVIDER} from "./shareService"; but when call _shareService. CheckUser.subscribe,i get error Checkuser is not defined!plz help me how to use it –  Jun 07 '16 at 09:39
  • did you add the `constructor(_shareService: shareService)` ? – Joel Almeida Jun 07 '16 at 09:44
  • absolutely yes... i have a shopService and give data from shareService...my shopService is injectable() and import to 3 component...i test it with push a alert in `constructor(){ alert() }`, the alert function 3 time execute...and my ` _shareService.CheckUser.subscribe()` function Too 3times execute...this means my constructor function execute number of import the own service...how to fix it?? i want just one time execute :( –  Jun 07 '16 at 10:21
  • and what arguments does your `shareService` constructor have? – Joel Almeida Jun 07 '16 at 10:24
  • nothing!!is empty i dont need to anything in my shareService –  Jun 07 '16 at 10:28
  • Create a plnkr reproducing the issue. Else is almost impossible to figure out the full problem. – Joel Almeida Jun 07 '16 at 10:31
0

The problem is that the service is singleton and the component subscribe to it each time it created or (I don't see the full code) at the point the

_shareService.CheckUser.subscribe

is placed , so CheckUser should be a method that returns an Observable . if you have plunkr I can edit it . Another semantic problem is that the observable should end with $ and not the BehaviorSubject.

Haddar Macdasi
  • 3,477
  • 8
  • 37
  • 59