簡體   English   中英

Angular 5 BehaviorSubject不適用於布爾值

[英]Angular 5 BehaviorSubject not working for boolean value

我正在嘗試用角度5來練習behaviorsubject。我編寫了一個包含兩個組件的小型應用程序,想同時更改兩個組件中的值,但該值沒有改變。 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);
  }


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

應該

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

this.isAdmin是一個BehaviorSubject並且您試圖設置!thisAdmin值為false

Stackblitz

將您的服務更改為:

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因為this.admin將僅是this.admin的對象

現場演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM