Angular Service没有明确的原因

时间:2018-04-22 13:21:03

标签: angular cordova

我定义了一个DataService组件,它有两个方法,一个是使用cordova-file-plugin从文件中读取,另一个是写入它。 它过去常常使用in-mem-web-api,而且效果非常好。我什么也没做,只是将这些功能改为使用file-API。 现在我有一个List组件,它可以做到这一点:

ngOnInit() {
    document.addEventListener("deviceready", this.getEntries) ;
    }

getEntries(): void {
    this.dataService.readFromFile(function(fileData) {
        this.entries = fileData;
    });
}

现在,当组件被初始化或加载时,例如从一个链接,调试器告诉我因为Cannot call method 'readFromFile' of undefined中的zone.js而出现TypeError,所以不知道服务是什么。但是,它只是在constructor(private dataService:DataService)中注入并在app.module中注册为提供者,所以我非常无知为什么会发生这种情况。

// edit:DataService的源代码:

import { Injectable } from '@angular/core';
import { Entry } from './entry';

declare var cordova;

@Injectable()
export class DataService {

    private pathToFile = cordova.file.directory + 'contact-list';

    constructor() { }

    readFromFile(callback) {
    console.log("readFromFile is called");
    (<any> window).resolveLocalFileSystemURL(this.pathToFile, function(fileEntry) {
        fileEntry.file(function(file) {
        var reader = new FileReader();

        reader.onloadend = function() {
            callback(JSON.parse(this.result));
        };

        reader.readAsText(file);
        });
    }, function ifNoFile
    [...]cut some stuff out here, because it really doesn't matter
        });
        });
    });
    }

    writeToFile(data): void {
    (<any> window).resolveLocalFileSystemURL(this.pathToFile, function(fileEntry) {
        fileEntry.createWriter(function(fileWriter) {
        fileWriter.truncate(0);
        fileWriter.write(JSON.stringify(data));
        });
    });
    }
}

1 个答案:

答案 0 :(得分:1)

更改您的事件监听器回调以使用arrow function或使用bind()保留this引用。

document.addEventListener("deviceready", e => this.getEntries());
相关问题