0

Please Check the below code. I am working on angular 2 generated by "Angular2 CLI" first time with the typescript. and i have been having an issue on calling class function inside anonymous function .

For Example i want to call readFile() function inside showDialog()

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))

1 Answer 1

1

Your function expression doesn't preserve the enclosing 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");
Sign up to request clarification or add additional context in comments.

1 Comment

Thank You :) . . .

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.