首页 > 解决方案 > 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

标签: angular

解决方案


我认为您的示例按描述工作,但您始终将值设置为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);
  }

}

推荐阅读