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

时间:2019-11-15 17:42:35

标签: angular dependency-injection angular-httpclient

我试图在服务中使用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,还是依赖注入可以解决这个问题?

1 个答案:

答案 0 :(得分:1)

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

之前:

byKey: function (key) {

之后:

byKey: key => {
相关问题