Search code examples
jsond3.jsangular-clicrossfilter

"Cannot read property 'length' of null" with Angular-cli and a json file


I've got a mistake when I want to load data in a json file in my angular-cli project

When I use a .csv file like this it's working properly :

Main.ts

const data = require('file-loader?name=[name].[ext]!./data/data.csv');

AppComponent.ts

constructor(private service: Service) {
    let psv = d3.dsv(";", "text/plain");
    let __self = this;
    psv("data.csv", function (data) {
        __self.service.emit({
            "data": data,
            "filter": crossfilter(data)
        });
    });
}

But when I want to use a .json file, with the next code :

Main.ts

const data = require('file-loader?name=[name].[ext]!./data/data.json');

AppComponent.ts

    constructor(private service: Service) {
    let __self = this;
    let psv = d3.json("data.json", function (data) {
        __self.service.emit({
            "data": data,
            "filter": crossfilter(data)
        });
    });
}

I got the following error in my web-browser :

EXCEPTION: Cannot read property 'length' of null

If someone have an idea, I'll be glad to know it!

[EDIT]

I follow the Gordon instructions, and I have made a console.log(error) and it returns

SyntaxError: Unexpected token m in JSON at position 0
at JSON.parse (<anonymous>)
at Object.d3_json (eval at module.exports (addScript.js:9), <anonymous>:9540:17)
at XMLHttpRequest.respond (eval at module.exports (addScript.js:9), <anonymous>:1944:29)
at XMLHttpRequest.wrapFn [as _onload] (zone.js:1190)
at ZoneDelegate.invokeTask (zone.js:363)
at Object.onInvokeTask (ng_zone.js:264)
at ZoneDelegate.invokeTask (zone.js:362)
at Zone.runTask (zone.js:166)
at XMLHttpRequest.ZoneTask.invoke (zone.js:416)`

And in the browser console, in the Source tab, by clicking on the data.json, I have this :

module.exports = __webpack_public_path__ + "data_mares.json";


Solution

  • Thank you for your help Gordon

    I follow your instructions, and I have made a console.log(error) and it returns

    SyntaxError: Unexpected token m in JSON at position 0
    at JSON.parse (<anonymous>)
    at Object.d3_json (eval at module.exports (addScript.js:9), <anonymous>:9540:17)
    at XMLHttpRequest.respond (eval at module.exports (addScript.js:9), <anonymous>:1944:29)
    at XMLHttpRequest.wrapFn [as _onload] (zone.js:1190)
    at ZoneDelegate.invokeTask (zone.js:363)
    at Object.onInvokeTask (ng_zone.js:264)
    at ZoneDelegate.invokeTask (zone.js:362)
    at Zone.runTask (zone.js:166)
    at XMLHttpRequest.ZoneTask.invoke (zone.js:416)`
    

    And in the browser console, in the Source tab, by clicking on the data.json, I have this :

    module.exports = __webpack_public_path__ + "data_mares.json";