[英]How to use inject outside class in pure function in angular v14?
I want to inject my FooService
and use it only when I click on the button.我想注入我的
FooService
并仅在单击按钮时使用它。
But I got this error:但我得到了这个错误:
Error: NG0203: inject() must be called from an injection context (a constructor, a factory function or a field initializer)
Is there a way to make it work by inject
will be in a separate function?有没有办法通过
inject
使其工作将在单独的 function 中?
import { Component, inject, VERSION } from '@angular/core';
import { FooService } from './foo.service';
const load = () => {
const foo = inject(FooService);
foo.doSome();
};
@Component({
selector: 'my-app',
template: `in app! <button (click)="onClick()">click </button>`,
})
export class AppComponent {
name = 'Angular ' + VERSION.major;
onClick() {
load();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.