Angular 5 BehaviorSubject不适用于布尔值

时间:2018-03-27 11:29:28

标签: javascript angular angular5 behavior

我正在尝试在角度5中练习行为主题。我写了一个包含两个组件的小应用程序,并希望立即更改它们中的值,但值不会更改。 BehaviorSubject应该更改所有组件中的值。请帮我理解。

服务

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);
}

}

组件一

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);
  }

}

组件一html

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

第二部分

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);
  }


}

2 个答案:

答案 0 :(得分:4)

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

应该是

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

this.isAdminBehaviorSubject,您试图将!thisAdmin设置为false

Stackblitz

答案 1 :(得分:1)

将您的服务更改为:

y = c[N:]

它应该是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); } } ,因为this.isAdmin.value只会是行为主题的对象

Live Demo