Angular 4 Subject subscribe在2个模块之间共享

时间:2018-05-24 11:04:34

标签: angular typescript service subject

我目前的设置:

共享-module.ts:

 import {ModuleWithProviders, NgModule} from '@angular/core';
import { CommonModule } from '@angular/common';
import { HeaderComponent } from './header/header.component';
import {LayoutService} from './services/layout.service';

@NgModule({
  imports: [
    CommonModule
  ],
  exports: [
    HeaderComponent
  ],
  declarations: [HeaderComponent]
})
export class SharedModule {

  static forRoot(): ModuleWithProviders {
    return {
      ngModule: SharedModule,
      providers: [LayoutService]
    };
  }
}

layout.service.ts:

import { Injectable } from '@angular/core';
import {Subject} from 'rxjs/Subject';


@Injectable()
export class LayoutService {

  constructor() { }


  VisibleSubject$ = new Subject<boolean>();


  EnableButton (): void {
    this.VisibleSubject$.next(true);
    console.log('Visible Subject returns:', true);
  }

authorization.service.ts:

import { Injectable } from '@angular/core';
import {LayoutService} from '../shared-module/services/layout.service';
import {VoidService} from '../shop/void.service';



@Injectable()
export class AuthorizationService {

  constructor(private layoutservice: LayoutService,
              private voidserv: VoidService) {}
  // just for test
  private credentials = {
    login: 'admin',
    password:  'admin'
  };

  private isLogged = false;

  login(login, password) {
    return new Promise((resolve, reject) => {
      if (this.credentials.login === login && this.credentials.password === password) {
        this.isLogged = true;
        this.layoutservice.EnableButton();

        resolve();
      } else {
        reject();
      }
    });
  }

shop.module.ts:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import {ProductsComponent} from './products/products.component';
import { ...}


@NgModule({
  imports: [
    RouterModule,
    CommonModule,
    LoginModule,
    ShopRoutingModule,
    ReactiveFormsModule,

    SharedModule

  ],
  exports: [ProductsComponent],
  providers: [ShopResolve, FootserviceService],
  declarations: [ProductsComponent... ShopComponent]
})
export class ShopModule { }

products.component.ts:

import {...}




@Component({
  selector: 'app-products',
  templateUrl: './products.component.html',
  styleUrls: ['./products.component.less']
})
export class ProductsComponent implements OnInit, AfterViewInit {

  visible: boolean = false;


                         // 3 Services in Constructor
  constructor(private shopservice: ShopService,
              private routerService: Router,
              private lay: LayoutService,
             ) { }

  ngOnInit() {
    this.lay.VisibleSubject$.subscribe((value) => {
      this.visible = value;
      console.log('Visible: ', this.visible); });
    ...
  }

问题是什么? 在此之后,我无法在products.component上订阅我的值:

this.lay.VisibleSubject$.subscribe((value) => {
          this.visible = value;
          console.log('Visible: ', this.visible); });
        ...
      }

控制台是空的,值仍未定义,我尝试了很多解决方案,但任何事情都适合我。 登录引擎工作正常,它在控制台上返回我:

Subject {_isScalar: false, observers: [], closed: false, isStopped: false, hasError: false, …}

但是如果我想订阅这个主题,每当我登录并注销时,每次都会返回false :(

我是初学者,但对服务的理解让我兴奋不已。 有人能说出我做错了什么吗? 我的共享模块有问题吗? 请回答我

1 个答案:

答案 0 :(得分:0)

现在可以使用,但只能使用BehaviorSubject(null)并且在Lazy Loading ShopModule上使用Guard CanLoad。 有人可以解释一下原因吗?

应用路由模块:

import {Class, NgModule} from '@angular/core';
import {PreloadAllModules, Route, RouterModule, Routes} from '@angular/router';
import {CanloadGuard} from './authorization/canload.guard';
import {MainAboutComponent} from './about/main-about/main-about.component';
import {PageNotFoundComponent} from './shared-module/page-not-found/page-not-found.component';
import {InfoContactComponent} from './contact/info-contact.component';




const APP_ROUTES : Routes = [
      {path: '', pathMatch: 'full', redirectTo: 'shop'},
              //The Most important!! Delete ShopModule from app.module!!!
  {path: 'shop', canLoad: [CanloadGuard], loadChildren: 'app/shop/shop.module#ShopModule'},
  {path: 'about' , component: <any>MainAboutComponent},
  {path: 'contact', component: <any>InfoContactComponent},
  {path: '**', component: PageNotFoundComponent}

];

LayoutService:

VisibleSubject$ = new BehaviorSubject<boolean>(null);