我创建了一些可读写json文件的javascript函数,假设它们使用jsonfile库以angular(从打字稿代码中)调用。
这是代码:

function savePatient(patient){
    const jsonfile = require('jsonfile')
    const file = 'src/resources/patients.json'
    jsonfile.writeFile(file, patient, {flag: 'a'}, function(err){
        if(err) console.error(err)
    })
}

function getPatients(){
    const jsonfile = require('jsonfile')
    const file = 'src/resources/patients.json'
    jsonfile.readFile(file, function(err, obj){
        if(err) console.error(err)
        console.dir(obj)
        return obj
    })
}


这是Angular组件中的函数声明:

declare function savePatient(patient: Patient);
declare function getPatients(): Patient[];


我设法成功调用了savePatient()函数,它按预期执行。

当我尝试从Angular组件内部调用console.log(getPatients())时,输出未定义,但是getPatients()函数本身会从console.dir(obj)行生成正确的控制台输出。

我应该如何在Angular组件中获取正确的函数值?

同样,如果有人发现这个项目相关的话,这个项目也将放在电子容器内。

我发现有趣的是Angular组件是第一个向控制台输出信息的组件,尽管考虑到Angular组件应依赖于js函数的返回值,尽管js函数应该在其之前提供输出是有意义的,但我不知道该怎么做。

最佳答案

您的职能

function getPatients(){
    const jsonfile = require('jsonfile')
    const file = 'src/resources/patients.json'
    jsonfile.readFile(file, function(err, obj){
        if(err) console.error(err)
        console.dir(obj)
        return obj
    })
}


异步工作(请参见docs)。

您有两个选择。第一个是异步处理文件读取:

function getPatients(){
    const jsonfile = require('jsonfile')
    const file = 'src/resources/patients.json';
    // Create a new promise
    return new Promise((resolve, reject) => {
        jsonfile.readFile(file, function(err, obj){
            if(err){
                console.error(err)
                return reject(err);
            }
            console.dir(obj)
            return resolve(obj);
        });
    });
}

...

// Prints the read object in the console, after the file reading is done
getPatients().then((obj) => {
    console.dir(obj);
});


第二种选择,我认为对您来说最好的解决方案是使用同步方式读取文件:

function getPatients(){
    const jsonfile = require('jsonfile')
    const file = 'src/resources/patients.json'
    try {
        const obj = jsonfile.readFileSync(file);
        console.dir(obj);
        return obj;
    } catch(e) {
        console.error(e);
    });
}

08-06 04:41