Has*_*iri 4 javascript behavior angular angular5
我正在尝试用角度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);
}
}
Run Code Online (Sandbox Code Playgroud)
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);
}
}
Run Code Online (Sandbox Code Playgroud)
<button (click)="changeValue()">Click Me</button>
<p>
one {{isAdmin}}
</p>
Run Code Online (Sandbox Code Playgroud)
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);
}
}
Run Code Online (Sandbox Code Playgroud)
changeAdmin(){
this.isAdmin.next(!this.isAdmin);
}
Run Code Online (Sandbox Code Playgroud)
应该
changeAdmin(){
this.isAdmin.next(!this.isAdmin.value);
}
Run Code Online (Sandbox Code Playgroud)
this.isAdmin是一个,BehaviorSubject而您尝试设置的!thisAdmin结果是false
| 归档时间: |
|
| 查看次数: |
1976 次 |
| 最近记录: |