首页 > 解决方案 > 角度如何从可观察订阅的结果中设置组件变量

问题描述

Angular 前端调用必须返回 observable 的服务。我需要将调用组件的变量设置为服务可观察的值,但我找不到访问组件变量的方法。

希望我不会错过一些琐碎的事情,这就是我尝试过的。

@Component
   metadata
 export class AppComponent {
    hexResult: string = '';   <-- this needs to be set with data from the service

该服务使用文件读取器读取本地文件。服务有 reader.onLoadend 读取完成时触发。稍微按摩一下数据后,我使用从组件传递到服务的 BehaviorSubject 来发回结果。
但是组件必须订阅 Behavior 主题。然后它可以对结果进行更多处理,但无法将结果返回给组件,组件需要它来影响 html。

这是通过 BehaviorSubject(“binaryRetrieved”)接收数据的组件中的代码:

  this.binaryRetrieved.subscribe( (binString) => {
      console.log('received raw binary');
      if (binString && binString.length > 0) {
          this.hexResult = this.binService.binaryToHexString(binString);
      }
  });

“this.hexResult”未定义,因为它在组件声明中看不到 hexResult。

我迷路了……有什么提示吗?

提前致谢。瑜伽士

标签: javascriptangularevent-handlingfilereadersubscribe

解决方案


我很抱歉在这个问题上浪费了人们的时间。如果我再聪明一点,我会更快地找到解决方案。

所有组件变量都可以从可观察响应的 subscribe/error/complete 部分中访问。我的问题是:我在组件中声明了一个变量,但没有初始化(实例化)它;因此它似乎是“未定义的”。

多么浪费我的时间找到它,但我更抱歉浪费了你的时间。

瑜伽士。


推荐阅读