![](/img/trans.png)
[英]Calling Typescript function from JavaScript file in Angular
[英]angular 2 typescript calling function
请检查以下代码。 我的工作angular 2
由“Angular2 CLI”第一次与打字稿生成。 我一直在匿名函数内部调用类函数时遇到问题。
例如我想在showDialog()
调用readFile()
函数
我在想什么! 错〜
对不起我的英语不好。
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();
});
});
}
}
在组件中:
this.selectfileservice.showDialog().subscribe(x => console.log(x))
您的函数表达式不会保留this
。 改用箭头功能:
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.