简体   繁体   中英

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

Angular front-end calls a service that must return 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. After massaging the data a bit, I use a BehaviorSubject passed from the component to the service to send back the result.
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.

This is the code in the component that is receiving the data via 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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