简体   繁体   English

角2打字稿调用功能

[英]angular 2 typescript calling function

Please Check the below code. 请检查以下代码。 I am working on angular 2 generated by "Angular2 CLI" first time with the typescript . 我的工作angular 2由“Angular2 CLI”第一次与打字稿生成。 and i have been having an issue on calling class function inside anonymous function . 我一直在匿名函数内部调用类函数时遇到问题。

For Example i want to call readFile() function inside showDialog() 例如我想在showDialog()调用readFile()函数

What am i thinking! 我在想什么! wrong~ 错〜

Sorry For my English. 对不起我的英语不好。

import {Injectable} from '@angular/core';
import {Observable} from "rxjs";
import "rxjs/Rx";

@Injectable()
export class SelectFileService {

    ImageExtensions: string[] = ['jpg', 'jpeg', 'png', 'gif'];

    constructor() {
    }


    public showDialog(): Observable<string[]> {
        return Observable.create((observer) => {
            dialog.showOpenDialog({
                properties: ['multiSelections'],
                filters: [
                    {name: 'Images', extensions: this.ImageExtensions}
                ]
            }, function (fileNames) {
                if (fileNames === undefined) {
                    observer.error("ERROR");
                    return;
                } else {
                    observer.next(fileNames);
                    observer.complete();
                    //Tried Below and not working
                    // this.readFile(fileNames[0]);
                    // Also tried java type
                    // SelectFileService.readFile(fileNames[0]);
                }
            });
        });
    }

    public readFile(filePath: string): Observable<string> {
        return Observable.create((observer) => {
            fs.readFile(filePath, 'utf-8', function (err, data) {
                if (err) {
                    observer.error(err.message);
                }
                observer.next(data);
                observer.complete();
            });
        });

    }
}

In Component: 在组件中:

this.selectfileservice.showDialog().subscribe(x => console.log(x))

Your function expression doesn't preserve the enclosing this . 您的函数表达式不会保留this Use an arrow function instead: 改用箭头功能:

 return Observable.create((observer) => {
            dialog.showOpenDialog({
                properties: ['multiSelections'],
                filters: [
                    {name: 'Images', extensions: this.ImageExtensions}
                ]
            }, (fileNames) => { // <---- here ----
                if (fileNames === undefined) {
                    observer.error("ERROR");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM