Access variables declared a component from a RxJS subscribe() function

后端 未结 2 449
时光取名叫无心
时光取名叫无心 2020-12-17 16:58

I am able to use this.variable to access variables in any part of the component, except inside RxJS functions like subscribe() or catch()

2条回答
  •  -上瘾入骨i
    2020-12-17 17:23

    As an alternative to @drewmoore's answer, if you wish to have external functions you can do:

     .subscribe((location) => dataHandler(location), (error) => errorHandler(error));
    
     ....
    
     const dataHandler = (location) => {
         ...
     }
    

    By externalising the errorHandler function, it can be used in multiple places (ie. subscriptions). By having as (fat) arrow functions your code will capture the 'this' context (as discussed in @Drewmoore's answer).

    What is lacking is the ability to write the following and have handled like an arrow function. The following works and passes the argument implicitly. Unfortunately AFAIK you cannot capture the this context (perhaps use bind to achieve this, though that makes the code more verbose overall).

     .subscribe(dataHandler, errorHandler);
    

    This is soooo succinct! But alas won't work if the context is required.

提交回复
热议问题