gpt4 book ai didi

javascript - Angular 5 BehaviorSubject 不适用于 bool 值

转载 作者:行者123 更新时间:2023-12-04 23:13:21 25 4
gpt4 key购买 nike

我正在尝试在 Angular 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.isAdminBehaviorSubject并且您试图设置 !thisAdmin计算结果为 false
Stackblitz

关于javascript - Angular 5 BehaviorSubject 不适用于 bool 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49511732/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com