我正在尝试在角度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);
}
}
<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);
}
}
答案 0 :(得分:4)
changeAdmin(){
this.isAdmin.next(!this.isAdmin);
}
应该是
changeAdmin(){
this.isAdmin.next(!this.isAdmin.value);
}
this.isAdmin
是BehaviorSubject
,您试图将!thisAdmin
设置为false
答案 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
只会是行为主题的对象