简体   繁体   English

如何在 angular v14 中的纯 function 中使用 class 外部注入?

[英]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 中?

stackblitz 堆栈闪电战

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();
  }
}

I'm afraid this is not possible.恐怕这是不可能的。

You can find an explanation of the error and all possible valid ways of using inject here .您可以在此处找到错误说明以及使用inject的所有可能有效方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM