无法从我的角度库组件中导入json

时间:2018-07-12 19:46:52

标签: angular angular-cli angular-cli-v6

如果您想帮助我检查发生了什么,这里是Github中的存储库:https://github.com/sandrocsimas/ngx-material-palette-picker

我正在尝试创建我的第一个角度库。 我通过使用角度cli命令生成了代码:

ng new ngx-material-palette-picker-app
ng generate library ngx-material-palette-picker

在组件NgxMaterialPalettePickerComponent中,我正在导入一个json文件,但是该构建引发了以下错误:

projects/ngx-material-palette-picker/src/lib/ngx-material-palette-picker.component.ts(2,31): error TS2307: Cannot find module './palettes.json'.

这是我的组件:

import {Component, OnInit} from '@angular/core';
import * as palettesJSON from './palettes.json';

@Component({
  selector: 'ngx-mpp',
  template: `,
  styles: []
})
export class NgxMaterialPalettePickerComponent implements OnInit {

  constructor() {

  }
}

我在根路径中创建了一个名为types的目录,并将以下代码添加到index.d.ts:

declare module '*.json' {
  const value: any;
  export default value;
}

我还在主tsconfig.json中将目录types添加到typeRoots

"typeRoots": [
  "node_modules/@types",
  "types"
],

该项目在Sublime编辑器中没有显示任何错误,但是当我尝试使用命令ng build --prod ngx-material-palette-picker构建该项目时,出现了此问题开头描述的错误。如何解决这个问题?

3 个答案:

答案 0 :(得分:0)

JSON文件应放置在有角度的已知搜索位置(例如“ src / assets”)。 您应该按照以下答案中的说明将“ JSON”文件的路径添加到“ assets”下的angular.json中:Import json file in typescript Angular 5

或者,您也可以通过http请求获取JSON文件的内容。尽管我相信上述方法在这种情况下仍然适用。

答案 1 :(得分:0)

这是通过httpClient使用服务的方式,我以动态形式使用它(最终json将来自服务器,但现在使用json文件):

@Injectable()
export class QuestionService {

constructor(private httpClient: HttpClient) { }

public getQuestions(clientName: string): Observable<any> {
    return this.httpClient.get(`./assets/${clientName}.json`);
}

}

json file:
{
"search":   [
    {
        "key": "contract",
        "label": "Contract",
        "value": "",
        "required": true,
        "order": 1,
        "type": "text"
    },
    {
        "key": "vendor",
        "label": "Vendor",
        "value": "",
        "required": true,
        "order": 1,
        "type": "text"
    },
    {
        "key": "status",
        "label": "Status",
        "value": "",
        "required": true,
        "order": 1,
        "type": "text"
    },
    {
        "key": "from",
        "label": "From",
        "value": "",
        "required": true,
        "order": 1,
        "type": "text"
    },
    {
        "key": "to",
        "label": "To",
        "value": "",
        "required": true,
        "order": 1,
        "type": "text"

    }
],
"client": {
    "firstName": "harvey",
    "lastName": "2face"
}
}

答案 2 :(得分:0)

您是否使用了编译器选项 resolveJsonModule? 尝试通过元素 "resolveJsonModule": truetsconfig.app.json 放入文件 compilerOptions。它对我有用。

对于单元测试,请检查文件 tsconfig.spec.json 以获取相同的技巧。

相关问题