for components and its children. It is higher in the hierarchy than the element injector in the...
everything inject first,inject 不到的地方用 injector.get 来代替,injector.get 不灵时就 wrap runInInjectionContext。 everything injector.get,统一,真的没办法 (比如调用组件外的函数,它里面需要注入,但又不想 passing injector) 才 wrap 一层 runInInjectionContext 使用 inject。 constructor, OnInit, Conten...
因为inject 没有在 injection context 中,只有 constructor 阶段才处于 injection context 内。 我们可以通过 runInInjectionContext 来处理。 class ServiceA { injector=inject(Injector); method() { runInInjectionContext(this.injector, () =>{ const serviceB=inject(ServiceB); }); } } 这样就 ok 了。
Angular 引入了一个 EnvironmentInjector 注入器和 runInInjectionContext 函数可以解决此问题,在构造函数或者属性初始化的时候注入 EnvironmentInjector 并保存到属性中,之后通过调用 runInInjectionContext 函数传入 EnvironmentInjector,那么在回调函数中使用 inject 函数,这个回调函数注入上下文就是 EnvironmentInjector 实例化...
| [](https://github.com/angular/angular/commit/0814f2059406dff9cefdd8b210756b6fdcba15b1) | introduce `runInInjectionContext` and deprecate prior version (#49396) | ...
我尝试了许多不同的解决方案,包括使用fakeAssunc+tick、TestBed.flushEffects、runInInjectionContext和许多其他不符合编写测试目的的黑客解决方案。 Example: @Injectable({ providedIn: 'root' }) export class ServiceA { private signalA: Signal<number> = signal(0); ...
| [](https://github.com/angular/angular/commit/6acae1477a212bbd85d0670913c2925fa3bc0c24) | Add `TestBed.runInInjectionContext` to help test functions which use `inject` (#47955) | ...
When buildling the app, I get an inject() must be called from an injection context such as a constructor, a factory function, a field initializer, or a function used with runInInjectionContext.. After days of debugging, I've managed to pin down the problem to the DI between our shared...
runInInjectionContext(getUsers).subscribe((users) => { expect(users.length).toBe(1); }); controller.expectOne('users').flush([{ id: 1 }]); }); }); The createContext() function returns SpectatorInjectionContext with the following properties: inject() - A proxy for Angular TestBed....
name + '() can only be used within an injection context such as a constructor, a factory function, a field initializer, or a function used with `runInInjectionContext`')); } } 所以一般在constructor使用即可,如下所示 @Component({ selector: 'my-app', standalone: true, template: ` ...