角度2:如何在多个组件之间共享一项服务? [英] Angular 2: how to share one service among several components?

查看:48
本文介绍了角度2:如何在多个组件之间共享一项服务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的角度应用程序中有一些服务可以像这样存储用户状态:

I have some service in my angular application like this to store the status of user:

public activeUser = new BehaviorSubject(null);

我执行以下操作:

转到组件A,并在构造函数中我已订阅了此Subject(auth是service,已导入):

Go to the component A and in constructor I have subscribed on this Subject (auth is service, which has been imported):

    this.auth.activeUser.subscribe((status) => {
        console.log("subscribe >>>", status);
        this.isAuth = status;
    });

在此组件的另一种方法中,我这样做:

In another method of this components I do this:

this.auth.activeUser.next(true);

如果用户成功登录,则在遇到一些麻烦时设置为false.

if user login successfully, and set false if some troubles.

太好了,它可以正常工作,我有控制台输出.

Greate, it works, I have got console output.

但是我还有另一个组件,该组件必须使用 activeUser 状态.在此组件中,我导入了服务,然后执行以下操作:

But I have another component, which must use activeUser status. In this component I imported service and do the follow:

ngOnInit() { 
       this.auth.activeUser.subscribe(
          (userStatus:boolean) => {
              this.isAuth = userStatus;
              console.log("this is foo HomeComponent", this.isAuth);
          }
      );
      console.log("home activeUser", this.auth.activeUser);
  }

我认为,当在第一个组件中 Subject 获得 next(true) next(false)时,我必须看到 this在控制台中是foo HomeComponent ,但这不是真的.

I consider that when in first component Subject gets next(true) or next(false) I have to see this is foo HomeComponentin console, but it's not true.

我找到了这个答案 Subscribe方法不会对更改做出反应[Angular 2]

根据它,我已经完成了以下操作:

and according to it I have done the follow:

  1. 转到app.module.ts
  2. 导入的服务
  3. 向服务提供商添加服务[]

嗯,我希望我的问题能得到解决.但不是.我返回了第二个组件,并删除了带服务的导入.但是现在我无法编译代码:

Hmmm, I hoped that my problem will be soled. But no. I returned to my second component and removed the import with service. But now I can't compile the code:

this.auth.activeUser.subscribe 

其中 auth 是注入服务.我什至已经重新启动了webpack,但是无论如何还是失败了.谢谢您的帮助.

where auth is injected service. I have even restarted webpack, but anyway fails. Thanks you for help.

第二个组件在那里:

import {Component, OnInit} from '@angular/core';
import {AuthService} from "../../platform/auth.service";
import {Observable} from "rxjs";


@Component({
    selector: 'home-page',
    templateUrl: 'home.component.html',
    styleUrls:['home.component.scss']

})

export class HomeComponent  implements OnInit {
    public isAuth: boolean;
    constructor(private auth: AuthService) {
        this.isAuth = true;
    }

   ngOnInit() { 
       this.auth.activeUser.subscribe(
          (userStatus:boolean) => {
              this.isAuth = userStatus;
              console.log("this is foo HomeComponent", this.isAuth);
          }
      );
      console.log("home activeUser", this.auth.activeUser);
  }

}

我的app.module.ts

My app.module.ts

 import {AuthService} from "./platform/auth.service";

@NgModule({
    imports: [
        BrowserModule,
        // CommonModule,
        ReactiveFormsModule,
        routing,
        ModalModule,
        NgbModule,
        HttpModule
    ],
    declarations: [
        AppComponent,
        HomeComponent
    ],

    providers: [
        appRoutingProviders, AuthService
    ],
    bootstrap: [ AppComponent]
})
export class AppModule { }

我的服务:

@Injectable()
export class AuthService {


    public activeUser = new BehaviorSubject(null);

    constructor(private http: Http, private interaction:InteractionService) {

    }
}

推荐答案

我认为您需要的是ReplaySubject.这将重播新订阅者订阅时流中的最后一个事件.创建这样的一个:

I think what you need is a ReplaySubject. This will replay the last event that was on the stream when a new consumer subscribes. Create one like this:

   // 1 is the amount of events to replay when subscribed
   new ReplaySubject<boolean>(1); 

您可以使用与 BehaviourSubject

这篇关于角度2:如何在多个组件之间共享一项服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆