angular 2 subscribe shareService工作两次或几次

时间:2016-06-07 08:17:12

标签: javascript angularjs typescript angular rxjs

我在角度2中有一个ShareService,

******************************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);
    }
}

和我的另一个组件subscibe 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);

            }

        });

我的问题是我执行一次this.isLogin$.next(bool)但是订阅功能执行了两次或几次!我的篮子功能是一个xhr请求,这意味着当用户在我获得服务器的几个请求!!!我无法解决它...我不知道这个问题是角2或没有,任何人有这个问题? 持续几天我参与了这个问题!

2 个答案:

答案 0 :(得分:0)

问题是您的shareService正在获得多个实例。

其中一个解决方案是强制服务成为单身人士。

这样的事情应该有效:

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*/);
    }
  })
];

当前构造函数所需的所有内容都应放在constructor args

所在的位置

现在,在您的组件上,您可以使用以下服务:

@Component({
  providers: [SHARE_SERVICE_PROVIDER]
})

然后你可以像平时那样打电话。

另一种解决方案是将当前服务注入应用程序的主要组件。有关详细信息,请参阅here

答案 1 :(得分:0)

问题是该服务是单例,并且组件每次创建时都订阅它,或者(我没有看到完整代码)

_shareService.CheckUser.subscribe
放置了

,因此CheckUser应该是一个返回Observable的方法。如果你有plunkr我可以编辑它。 另一个语义问题是observable应该以$而不是BehaviorSubject结束。