简体   繁体   English

Angular 5 BehaviorSubject不适用于布尔值

[英]Angular 5 BehaviorSubject not working for boolean value

I am trying to practice behaviorsubject in angular 5. I am written a small app with two components and want to change the value in both of them at once but the value is not changing. 我正在尝试用角度5来练习behaviorsubject。我编写了一个包含两个组件的小型应用程序,想同时更改两个组件中的值,但该值没有改变。 BehaviorSubject should change the value in all the components. BehaviorSubject应该更改所有组件中的值。 Please help me understand. 请帮助我理解。

Service 服务

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


@Injectable()
export class TestserviceService {

public isAdmin = new BehaviorSubject<boolean>(false);
cast = this.isAdmin.asObservable();

constructor() { }

changeAdmin(){
  this.isAdmin.next(!this.isAdmin);
}

}

Component One 成分一

import { Component, OnInit } from '@angular/core';
import{ TestserviceService } from '../../testservice.service'; 

@Component({
  selector: 'app-one',
  templateUrl: './one.component.html',
  styleUrls: ['./one.component.css']

})
   export class OneComponent implements OnInit {
  isAdmin: boolean;
  constructor(private testservice: TestserviceService) { }


  ngOnInit() {
    this.testservice.cast.subscribe(data => this.isAdmin = data);

  }

  changeValue(){
    this.testservice.changeAdmin();
    console.log(this.isAdmin);
  }

}

Component One html 组件一html

<button (click)="changeValue()">Click Me</button>
<p>
  one {{isAdmin}}
</p>

Component Two 第二部分

import { Component, OnInit } from '@angular/core';
import { TestserviceService } from '../../testservice.service';

@Component({
  selector: 'app-two',
  templateUrl: './two.component.html',
  styleUrls: ['./two.component.css']
})
    export class TwoComponent implements OnInit {
  isAdmin: boolean;
  constructor(private testservice: TestserviceService) { }


  ngOnInit() {
    this.testservice.cast.subscribe(data => this.isAdmin = data);
    console.log("two "+this.isAdmin);
  }


}
changeAdmin(){
  this.isAdmin.next(!this.isAdmin);
}

Should be 应该

changeAdmin(){
  this.isAdmin.next(!this.isAdmin.value);
}

this.isAdmin is a BehaviorSubject and you were trying to set !thisAdmin which evaluates to false this.isAdmin是一个BehaviorSubject并且您试图设置!thisAdmin值为false

Stackblitz Stackblitz

Change your service to : 将您的服务更改为:

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
@Injectable()
export class SharedServiceService {

  constructor() { }
  public isAdmin = new BehaviorSubject<boolean>(false);
  cast = this.isAdmin.asObservable();

  changeAdmin(){
    this.isAdmin.next(!this.isAdmin.value);
  }
}

It should be this.isAdmin.value because this.admin will only be behaviourSubject's object 它应该是this.isAdmin.value因为this.admin将仅是this.admin的对象

Live Demo 现场演示

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

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