简体   繁体   English

角度如何从可观察订阅的结果中设置组件变量

[英]angular how to set a component variable from result in observable subscribe

Angular front-end calls a service that must return observable. Angular 前端调用一个必须返回 observable 的服务。 I need to set the calling component's variable to a value from the service's observable, but I can't find a way to access the component variable.我需要将调用组件的变量设置为服务的可观察值,但我找不到访问组件变量的方法。

Hoping I'm not missing something trivial, here is what I tried.希望我没有遗漏一些微不足道的东西,这就是我尝试过的。

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

The service uses a filereader to read a local file.该服务使用文件读取器读取本地文件。 Service has reader.onLoadend that is triggered when the read is complete.服务具有读取完成时触发的 reader.onLoadend。 After massaging the data a bit, I use a BehaviorSubject passed from the component to the service to send back the result.稍微修改数据后,我使用从组件传递到服务的 BehaviorSubject 来发回结果。
But the component has to Subscribe to the Behavior subject.但是组件必须订阅行为主题。 It then can process the result more, but cannot get the result back to the component, which then needs it to affect the html.然后它可以对结果进行更多处理,但无法将结果返回给组件,组件需要它来影响 html。

This is the code in the component that is receiving the data via BehaviorSubject ("binaryRetrieved"):这是通过 BehaviorSubject(“binaryRetrieved”)接收数据的组件中的代码:

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

"this.hexResult" is undefined because it can't see hexResult in the component declarations. “this.hexResult”未定义,因为它在组件声明中看不到 hexResult。

I'm lost... any hints?我迷路了……有什么提示吗?

Thanks in advance.提前致谢。 Yogi瑜珈

I am soooo sorry to have wasted people's time with this question.我很抱歉在这个问题上浪费了人们的时间。 If I had been a little smarter, I would have found the solution faster.如果我聪明一点,我会更快找到解决方案。

All component variables are accessible from within the subscribe/error/complete sections of an observable response.所有组件变量都可以从可观察响应的订阅/错误/完成部分访问。 MY PROBLEM WAS: I had DECLARED a variable in the component, but not INITIALIZED (instantiated) it;我的问题是:我在组件中声明了一个变量,但没有初始化(实例化)它; thus it appeared to be "undefined".因此它似乎是“未定义的”。

What a waste of my time to find it, but even more I apologize for wasting yours.找它真是浪费我的时间,但我更抱歉浪费了你的时间。

Yogi.瑜珈。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM