在Angular 12中,错误“Error: inject() must be called from an injection context”通常是由于在错误的上下文中调用了inject()方法引起的。这个错误通常出现在测试代码中,例如在组件的测试文件中。
要解决这个错误,你可以采取以下步骤:
例如,下面是一个错误的示例,其中inject()方法在错误的上下文中被调用:
it('should ...', inject([SomeService], (service: SomeService) => {
// 测试代码
}));
在这个例子中,inject()方法被错误地放置在it()块中,而不是在beforeEach()块中。要解决这个问题,你需要将inject()方法放置在正确的上下文中,如下所示:
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
SomeService
]
});
});
it('should ...', inject([SomeService], (service: SomeService) => {
// 测试代码
}));
例如,如果你在inject()方法中引用了SomeService,你需要在测试文件的顶部导入SomeService,如下所示:
import { SomeService } from 'path/to/some-service';
// 其他导入语句
describe('...', () => {
// 测试代码
});
通过遵循上述步骤,你应该能够解决“Error: inject() must be called from an injection context”错误,并成功在Angular 12中使用inject()方法。