首页 > 解决方案 > 在 JS 库中调用的 AppComponent 中声明的函数中未定义 Http

问题描述

试图调用一个函数,该函数从另一个 javascript 库 (AJV) 中的 http 响应返回一个承诺,但未定义的 httpClient 模块

问题是我们可以在任何其他节点模块中使用 appcomponent 导入的模块吗?

应用组件文件:

import { Component, OnInit } from '@angular/core';
import * as Ajv from 'ajv';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent implements OnInit{
  title = 'testajv';

  schema: any = {
   //Some Json Schema

  };

  ajv: any = new Ajv({loadSchema: this.loadSchema});
  validate: any = null;
  valid: any ;
  data: any = {
     "foo": ""
  };
  uri: string = "assets/schemas/defs.json";

  constructor(private http: HttpClient) {}

  ngOnInit(){

    this.ajv.compileAsync(this.schema).then(
      (validate) => {
        this.valid = validate(this.data);
        console.log(validate.schema);
      });
  }
  loadSchema(uri){
    return this.http.get(uri).toPromise().then(
      res => {
        return res;
      }
    )
  }


}

ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'get' of undefined
    TypeError: Cannot read property 'get' of undefined
        at Object.push../src/app/app.component.ts.AppComponent.loadSchema (app.component.ts:79)
        at loadMissingSchema (async.js:67)
        at _compileAsync (async.js:56)
        at async.js:32

标签: javascriptangularangular-httpclientajv

解决方案


您是否在 AppModule 中导入了 HttpClientModule ?


推荐阅读