在角度4中使用BehaviorSubject时,组件中的值不会更新(行为主题问题)

时间:2018-03-29 07:00:46

标签: angular rxjs

我正在使用Angular 4

我有一个核心组件,它是父组件(菜单,页眉,页脚......包含在核心组件中),如下所示

CoreComponentHTML

<div class="wrapper" [ngClass] = "{'confirmation-body' : (showConfirm == true)}">   
<app-header></app-header>
  <app-sidemenu></app-sidemenu>
  <div class="content-wrapper">    
    <app-breadcrumb> </app-breadcrumb>
  <router-outlet></router-outlet>
  </div>
</div>
  <footer class="main-footer">
    Copyright &copy; 2017 <strong><a href="">XXXXXXXXXXXXXX Solutions</a>.</strong> All rights reserved.
  </footer>

CoreComponent.ts

import { Component, OnInit,Injectable,AfterContentInit ,AfterViewInit, ViewEncapsulation, OnDestroy} from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { Event as RouterEvent,
  NavigationStart,
  NavigationEnd,
  NavigationCancel,
  NavigationError} from '@angular/router';
import {MenuService} from '../../shared/services/menu.service';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/toPromise';
import { ConfirmationSharedService } from 'app/sharecomponents/services/confirmation-shared.service';

@Component({
  selector: 'app-core',
  templateUrl: '../views/core.html'
})

export class CoreComponent implements OnInit, OnDestroy {
  public userPin: any;
  showConfirm: boolean;
  alive: boolean = false;
  constructor (private confirmationService: ConfirmationSharedService) {}

  setUserPin (responce) {
    console.log(responce, 'core pin core pin ')

    if (responce !== 0) {
      this.userPin = responce;
     }

  }

  ngOnInit() {
    this.confirmationService.getShowConfirm()
    .subscribe(suc => {
      console.log('1111111111111', suc);
      this.showConfirm = suc});

  }

  ngOnDestroy() {

  }
}

我在一个模块(xxxxxxxxxxxxx模块)中有一个LanguagesViewComponent,在另一个模块中有一个ConfirmationSharedService(此模块在CoreModule中导入)

我正在从LanguagesViewComponent设置一个BehaviourSubject的值,该值在ConfirmationSharedService中声明,如下所示

this.confirmService.setShowConfirm(true);

BehaviourSubject在ConfirmationSharedService

中声明如下
showConfirm: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);

    setShowConfirm(data) {
        this.showConfirm.next(data);
    }

    getShowConfirm(): Observable<boolean> {
        return this.showConfirm.asObservable();
    }

问题是当我在LanguagesViewComponent中将值设置为showConfirm时,CoreComponent中获得了新值(在CoreComponent中以ngOnInit()订阅)

0 个答案:

没有答案