'Inject a component's ATTRIBUTE into a Service

So I'm trying to make a service that will accept a parameter on construction. Idea is that it is not provided at root, but will be used similarly by several components. Each component would use a different instance of the service.

The service looks something like:

    import { Injectable, Inject } from '@angular/core'; @Injectable()
        
    export class SpecialService {
          constructor(
            @Inject('myArray') public myArray: any[]
          ) {}
    // Bunch of functions intended to mutate this array.
 

}

Then in a component I might have something like this:

@Component({
  selector: 'app-thing',
  templateUrl: './thing.component.html',
  styleUrls: ['./thing.component.css'],
  providers: [
    ArrayService,
    {
      provide: 'myArray',
      useValue: []
    }
  ]
})
export class ThingComponent implements OnInit {
constructor(
  private arrayService: ArrayService
){}

  dummy_array = // an array for purposes of testing

  ngOninit(){
  const httpArray = // get something from an HTTP call
  }
}

So What I want to do is rather than providing the service with a static empty Array, I want to provide it the dummy_array and eventually httpArray. I haven't found a way to do that without making simply binding myArray as a public attribute. I'd like to avoid that if possible, but most importantly, I'd like to use inject() properly here.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source