-1

I have the following typescript method

private processRequest<T>(request: Observable<T>, ...): Promise<T> {...}

request is an HttpClient Observable

processRequest(httpClient.get(url, ...));
...
processRequest(httpClient.post(url, ...));
...
  • Is it possible to retrieve url inside processRequest? If yes how? If not why?
  • Is it possible to change url inside processRequest? If yes how? If not why?
Franco Tiveron
  • 2,364
  • 18
  • 34

1 Answers1

1

Is it possible to retrieve url inside processRequest? [...] If not why?

In the general sense, in f(g(x)), f cannot access x, as it can only see what g returns, and that return value doesn't have to have knowledge over x at all. Consider g = u => 42 as a simple example of a function that doesn't retain the information about its input.

It would work if the return value retains that information. For example, for g = u => u (the identity function), f would of course know x because that's exactly what gets passed to it. This requires f to have this specific knowledge, though.

Since HttpClient#get returns Observable, this isn't the case here, though. This can be understood intuitively if you think about the fact that url is information specific to the logic of HttpClient, while Observable stems from RxJs which doesn't know anything about Angular. More directly, it can be seen by simply inspecting Obervable's type.

Is it possible to change url inside processRequest? [...] If not why?

This is now obvious, but you can't change what you can't access.

Ingo Bürk
  • 19,263
  • 6
  • 66
  • 100
  • Observable<> is not a function, is an object. What we do with it is calling methods, like subscribe, which act using internal status. In this case, the url must be buried somewhere in the status. In fact, we can provide an interceptor for the outgoing request (which is called after the Observable is created), which receives the full request. This means that that information is in the object and can be accessed at some level. – Franco Tiveron Jul 19 '21 at 23:28
  • But `#get` is a function. Anyway, observables are much closer to functions than you think. What actually happens with the URL is that it gets closed over in a function passed to the observable. No, you cannot access it. If you're convinced that you can, why ask this question? In that case just debug the object in the console and figure out which property it is. – Ingo Bürk Jul 20 '21 at 05:29
  • Interceptors, by the way, might be the answer to the question you didn't ask. But you asked a very specific question, and the answer to that is that it isn't possible. – Ingo Bürk Jul 20 '21 at 05:32