Skip to content

Routed components get services from the wrong injector #56774

@ItNoN

Description

@ItNoN

Which @angular/* package(s) are the source of the bug?

router

Is this a regression?

No

Description

It seems, routed components may have access to the injector, which they should not have.

For example:

export const ROUTES: Route[] = [
  {
    path: 'a-component',
    component: AComponent, // MyService is injected to AComponent
  },
  {
    path: 'b-component',
    providers: [MyService],
    component: BComponent,
  },
];

At first, we navigate to "b-component", then the "Route: b-component" child injector will be created, containing its own instance of MyService. After that, we navigate to "a-component", as result, AComponent get an instance of MyService from "Route: b-component" child injector.

When I met this behavior, I was a bit confused, since I thought, only BComponent can have access to the child injector.

We can observe the same thing with lazy-loading module injectors.

I assume, this situation is happening because of this pull request. Could you explain to me if this is intentional behavior? In my opinion, it may lead to unexpected bugs. Thank you.

Please provide a link to a minimal reproduction of the bug

https://stackblitz.com/edit/stackblitz-starters-hhtegu?file=src%2Fapp%2Fapp.component.ts

Please provide the exception or error you saw

No response

Please provide the environment you discovered this bug in (run ng version)

Angular CLI: 18.0.6
Node: 18.20.3
Package Manager: npm 10.2.3
OS: linux x64

Angular: 18.0.5
... animations, common, compiler, compiler-cli, core, forms
... platform-browser, router

Package                         Version
---------------------------------------------------------
@angular-devkit/architect       0.1800.6
@angular-devkit/build-angular   18.0.6
@angular-devkit/core            18.0.6
@angular-devkit/schematics      18.0.6
@angular/cli                    18.0.6
@schematics/angular             18.0.6
rxjs                            7.8.1
typescript                      5.4.5
zone.js                         0.14.7

Anything else?

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions