angular - Angular,行为主体,在一个组件中更改数据,在另一个组件中进行更改
问题描述
我有两个组件(没有关系)和一个服务。
点击 comp1 我需要在 comp1 和 comp2 中设置一些布尔值。
然后再次从 comp1 中单击,我需要在 comp2 中将布尔值设为 true。我用行为主题尝试了这个东西,但它没有捕捉到 comp2 中的变化。
基本上我在comp1中有点击功能,我需要点击comp2的变化。
comp1.ts
isValue = false
onclick(){
this.service..isValue = true
}
comp2.ts
isValue = false
ngOnInIt(){
this.isValue = true
console.log(this.isValue) /// true
then again turn this.isValue to false
}
这是行为主题的 stackblitz 链接 https://stackblitz.com/edit/angular-auuhng?file=app/two/two.component.ts
解决方案
我认为您的示例按描述工作,但您始终将值设置为true
(test-service.service.ts line 15: this.isAdmins.next(true);
),因此您不会看到后续点击有任何变化。如果您想在后续单击时切换真/假状态,您可以执行以下操作:
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
@Injectable()
export class TestServiceService {
curValue: boolean = false;
public isAdmins = new BehaviorSubject<boolean>(this.curValue);
cast = this.isAdmins.asObservable();
constructor() { }
changeAdmin() {
// toggle true/false:
this.curValue = ! this.curValue;
this.isAdmins.next(this.curValue);
}
}
推荐阅读
- postgresql - 如何使 postgres(光标?)从特定行开始
- javascript - React无法读取excel文件
- oop - 我无法通过调用默认构造函数来创建 ClassMirror 的新实例
- javascript - Next.js 是否在以下配置中为每个帖子生成一个页面?
- csh - csh 的撇号处理不清楚
- algorithm - 来自裸机的 scheme48 中的 GCD 功能
- python - 在 localhost 或命令行上运行包括 HTML 在内的 python 文件的问题
- c# - 按父母和孩子以及孩子的父母的顺序列表
- python - Python Scrapy - 根据第一个网页为每个条目保存一个“类别”
- loops - vue js无法读取未定义的属性