I want to use a service for getting information about the current coins the app supports.
Therefore I have created the Service: CoinsService
import { Injectable } from '@angular/core';
const coins = {
"btc":"bitcoin",
"ltc":"litecoin"
};
@Injectable()
export class CoinsService {
getCoins(){
return coins;
}
getSpecificCoin(coinShortcut: string) {
return coins[coinShortcut];
}
}
My user class looks like this:
import { CoinsService } from './coins.service';
export class User {
constructor(public id: number, public balance: number, public coinsService: CoinsService) {
console.log(coinsService.getCoins());
}
}
Before the service if I wanted to create a user I did it like this: let userA = new User('1','200');
Now with the service I need to pass in the coinService at object creation: let userA = new User('1','200', coinService)
For wholeness I post also the app.component.ts:
import { Component } from '@angular/core';
import { User } from './user';
import { CoinsService } from './coins.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [CoinsService]
})
export class AppComponent {
title = 'app';
constructor(private coinsService: CoinsService){
let userA = new User(1, 200, coinsService);
}
}
Are there any other options to be able to use the service in the User class without "passing it down" to the component which actually needs it?
I would like to create users without explicitly telling it everytime for every user that it needs a CoinsService.
It should be the standard that every user that gets created has access to it.
Also the service should be able to be used in every component below the App.Component. That's why I entered the CoinssService in the providers array.
Any help is appreciated.