0

I wrote a service to access the spotify api. In the constructor this service should get the access token. Therefore I call subscribe method on an Observable.

The problem with that:

The service gets injected into my main component. There I call methods of this service to receive data from spotify api. I think the problem is that the access token is not yet received before the first request to the api tries to use it.

How can I do so, that the service only gets injected after the constructor finished getting the access token?

Phil90
  • 138
  • 1
  • 16
  • You can't do that. Have your service treat the access token as an observable, and chain your requests onto that. – jonrsharpe Sep 01 '19 at 13:18
  • If delaying the page load until the access token is available is also an option (i.e if the token is absolutely crucial to your application) you can also consider using a [route guard](https://angular.io/guide/router#milestone-5-route-guards). – tomcek112 Sep 01 '19 at 13:24

1 Answers1

2

If you want to get the instance of a service but not injected through the constructor you may want to use injector.get method to get the instance. Something like -

const notificationService = this.injector.get(NotificationService);

For more details/example please refer -

https://medium.com/@aleixsuau/error-handling-angular-859d529fa53a, Inject a service manually, https://angular.io/api/core/Injector#get

Abhay
  • 483
  • 4
  • 12
  • 1
    This will not solve their problem as there will still be a race condition between the API request and the dependency resolution even if the service is initially provided in root. – tomcek112 Sep 01 '19 at 13:22