简体   繁体   English

角2订阅shareService工作两次或几次

[英]angular 2 subscribe shareService working twice or several times

I have a ShareService in angular 2, 我在角度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);
    }
}

and its my another component and subscibe the CheckUser ; 及其我的另一个组件并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);

            }

        });

my problem is i execute once this.isLogin$.next(bool) but subscribe function execute twice or several times !!!! 我的问题是我执行一次this.isLogin$.next(bool)但是订阅函数执行两次或多次! 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?? 我的购物篮功能是一个xhr请求,这意味着当用户登录时我将多个请求发送到服务器!我无法修复它...我不知道这个问题是否针对角度2,任何人都有这个问题? last a few days i Involved in this problem! 最近几天我卷入了这个问题!

The problem is that your shareService is getting multiple instances. 问题是您的shareService正在获取多个实例。

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 当前构造函数所需的所有内容均应放置在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. 有关更多信息,请参见此处

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 . 被放置,因此CheckUser应该是一个返回Observable的方法。 if you have plunkr I can edit it . 如果您有plunkr,我可以对其进行编辑。 Another semantic problem is that the observable should end with $ and not the BehaviorSubject. 另一个语义问题是,可观察对象应以$结尾,而不是BehaviorSubject。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM