注入的 HTTP 客户端未在运行时定义

Injected HTTP client isn't defined during runtime

我试图在服务中使用 Angular 的 HttpClient,但在运行时遇到以下错误:

ERROR TypeError: "this.http is undefined"

我正在 app.module.ts:

中导入 HttpClientModule
    import { HttpClientModule } from '@angular/common/http';
    ...

    @NgModule({
      imports: [
          HttpClientModule
          ...
      ],
      declarations: [AppComponent],
      bootstrap: [AppComponent]
    })

...并在我的 app.service.ts:

中导入 HttpClient
import { HttpClient } from '@angular/common/http';
import DataSource from 'devextreme/data/data_source';
...
@Injectable()
export class Service {
    constructor(private http: HttpClient) {}

    getDataSource(): DataSource {
        return new DataSource({
            byKey: function (key) {
                return this.http.get("https://localhost/foobar" + encodeURIComponent(key))
            }
        });
    }
}

this 是否因为在新对象中而引用不同的范围?我是否需要以某种方式传递 http,或者依赖注入是否涵盖了这一点?

尝试使用箭头函数确保您的 this 上下文引用当前 class 实例:

之前:

byKey: function (key) {

之后:

byKey: key => {