0

If a have a component providing it's own service:

@Component({
    selector: 'user-list',
    templateUrl: './user-list.component.html',
    styleUrls: ['./user-list.component.scss'],
    encapsulation: ViewEncapsulation.None,
    changeDetection: ChangeDetectionStrategy.OnPush,
    animations: fuseAnimations,
    providers: [
        TableSettingsService
    ]
})
export class UserListComponent {}

Can this TableSettingsService somehow get a reference of this component? I've tried

@Injectable()
export class TableSettingsService {
    constructor(
        persistentService: PersistentService,
        @Optional() @Self() persistentObject: UserListComponent
    ) {
        alert(!!persistentObject);
    }
}

What causes a circular dependency.

1 Answer 1

1

Get component that provided service

It is not the component that has provided the service. The service has been injected inside the component. Search to understand how dependency injection actually as a concept works. Then you will see why you can not achieve what you want.

You have used providers array in your component

providers: [
        TableSettingsService
    ]

So it is sure that UserListComponent will retrieve the service using the ElementInjector of <user-list> component.

Any children components of UserListComponent will also (if they not have their own providers array declaration for that service) retrieve the service from the the ElementInjector of <user-list> component.

In any case the service is injected inside the angular component. Not the other way around. So the service does not hold any reference to the component that uses it.

Sign up to request clarification or add additional context in comments.

1 Comment

Ah, ok! At this point the instance doesn't exist, yet! Thank you! So I'll need to find another way around. Can I get anything of the component who's injector created this service? Maybe the component type that caused the injector to be created? That'd be enough.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.