首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >角度9:可观察到的Getter返回对象,而不是从BehaviorSubject返回布尔值

角度9:可观察到的Getter返回对象,而不是从BehaviorSubject返回布尔值
EN

Stack Overflow用户
提问于 2020-08-04 16:52:56
回答 4查看 2.4K关注 0票数 0

如果这是在Stack溢出的某个地方,我很抱歉,但是我找不到一个对我有用的答案。

我有一个BehaviorSubject,它以布尔值的形式跟踪状态。我还有一个公共getter方法,它是一个可观察的返回BehaviorSubject的方法。我这样做不仅可以订阅BehaviorSubject值中的更改,而且还可以在未更改的情况下获得当前值。虽然我能够从订阅中获得适当的值,但在调用getter时,我将得到一个返回的对象。我要它返回最后一个值。

我试过使用.getValue(),它似乎不起作用,我也尝试过.value,它看起来确实有效,但在IDE中抛出了一个错误。

我创建了一个非常基本的示例来说明我要完成的任务,并在my.service.ts文件中添加了注释,以显示我要做的事情。请给我建议。谢谢!

编辑:默认情况下,我使用堆栈闪电战中的内容,并将getter分配给name变量来查看它。我的目标是得到价值,这样我就可以做一些基于价值是对还是错的事情。我肯定我错过了一些很简单的东西。

编辑:根据请求向问题添加代码

编辑:我还添加了.subscribe以表明,虽然我理解可观察性是如何工作的,但如果可能的话,我还想使用相同的getter检查值更改之外的值。

MyService

代码语言:javascript
运行
复制
import { Observable, BehaviorSubject } from "rxjs";

export class MyService {

  constructor() {}

  private _isBoolean = new BehaviorSubject<boolean>(false);

  public get isBoolean(): Observable<boolean> {
    //return this._isBoolean.value; // Returns boolean, but throws error "Type 'boolean' is not assignable to type 'Observable<boolean>'."
    return this._isBoolean; // Returns object, but I want the value
  }

}

AppComponent

代码语言:javascript
运行
复制
import { Component } from '@angular/core';
import { MyService } from './my.service';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name;

  constructor(private _myservice: MyService) {
    this._myservice.isBoolean.subscribe(val => {
      console.log("value from subscribe: " + val)
    })

    this.name = this._myservice.isBoolean;
    if (this._myservice.isBoolean) {
      console.log("true!");
    } else if (!this._myservice.isBoolean) {
      console.log("false!");
    }
  }
}

https://stackblitz.com/edit/angular-hhdgrc

EN

Stack Overflow用户

发布于 2020-08-04 17:15:51

您正在错误地使用Observables。请将subscribe调用添加到observable

代码语言:javascript
运行
复制
this._myservice.isBoolean.subscribe((val) => {
    this.name = val;
    console.log("value: " + val);
});

您只需在subscribe回调中添加代码即可使用更改的值:

app.component.ts 编辑

代码语言:javascript
运行
复制
import { Component } from '@angular/core';
import { MyService } from './my.service';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name;

  constructor(private _myservice: MyService) {
    this._myservice.isBoolean.subscribe(val => {
      console.log("value from subscribe: " + val);


      this.name = val ;
      if (val) {
        console.log("true!");
      } else if (!val) {
        console.log("false!");
      }
    })

  }
}
票数 3
EN
查看全部 4 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63251576

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档