0

I'm trying to pass string argument from component to a service constructor. In case of static value it was easy:

    @Component({
      selector: 'app-board',
      templateUrl: './board.component.html',
      styleUrls: ['./board.component.css'],
      providers: [UsersDetailProviderService,
                  {provide: 'boardId', useValue: 'whatever'} ]
    })

and at my service:

    constructor(private afs: AngularFirestore,
                @Inject('boardId') @Optional() public boardId?: string) {
        console.log(boardId);
    }

and I got my 'whatever' in the console. But what I really wanted to pass, is the real board id. In the component, I'm using activatedRoute to get board id to a local variable.

this.boardId = this.activatedRoute.snapshot.paramMap.get('id');

How can I pass this id to a service?

@edit I could achieve my goal by calling service method that takes board id as argument, and then initialize service data. But I don't think it's a good way to this?

Smokovsky
  • 569
  • 1
  • 7
  • 21
  • You can inject that service into your component and then assign your boardId value to service boardId value `this.userDetailsProviderService.boardId = this.activatedRoute.snapshot.parmMap.get('id')` – Arunkumar Ramasamy Feb 27 '20 at 05:42
  • 1
    @ArunkumarRamasamy : Thats what he dont want to do. Smolovsky : Why dont you think it's a good way ? – Shashank Vivek Feb 27 '20 at 05:44
  • @ShashankVivek Because then I will need to have an extra method in the service, which do what constructor would, and I will have to assign this id and call this method from a component. Do you think there is no better way to do it? – Smokovsky Feb 27 '20 at 05:52
  • @Smokovsky: IMHO, the constructor injection is used to provide some `Dependency Injection` for the `class`. If you start injecting such setter values using constructor injection, then we should really question the existence of `getter` and `setter` practices. You want to set some value in a class, you create a setter for easier readability and standard practice. Let me give some thought on this question though. Also, lets wait for others to comment on this – Shashank Vivek Feb 27 '20 at 05:59

0 Answers0