Raj Raj - 1 month ago 10
TypeScript Question

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

Answer

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");
Comments