Home > database >  Angular data service properties are undefined
Angular data service properties are undefined

Time:09-06

I'm using an Angular service to make requests with an SDK and another to manage wallet data. However, using the wallet-service within the SDK-service shows that the service does not exists.

Logging it within the SDK-service constructor shows {}

sdk-service

export class SdkService {
  constructor(private walletService: WalletService) {
    console.log(this.walletService); // {}
    ...

Since both services are singletons and provided forRoot what could be missing that the service is not injected and available?

CodePudding user response:

The services are injectable classes in Angular. They are a manifestation of the Singelton pattern in the design patterns terminology. Meaning you will have one single instance of the class/object initialized in the application lifecycle. When you have a cyclic injection issue the framework will throw a runtime error.

Back to your issue practically, you are using BehaviourSubject from RxJs. BehaviourSubject expects a default value. If you do not supply a default value it will send the current value as undefined. Thus, your problem in question. If you do not care about default value and only about latest emitted value then you just need to use Subject instead of BehaviourSubject.

private _wallets$: Subject<IWallet[]> = new Subject<IWallet[]>();

The other option to guard against the value of the stream being accessed before it gets initialized is to add a conditional statement before subscribing

Edit: You updated the OP, so please provide the error you are getting or the structure of your modules

  • Related