Nativescript在image-picker函数

时间:2017-12-15 16:03:41

标签: javascript android xml nativescript

我正在使用image-picker插件。我可以打开图片库并选择单个或多个图像。

我的问题是如何将图像的路径绑定到xml图像src ?!它在getImage()函数中不起作用。

XML:

<Image class="imageSource" src="{{ thumb }}" stretch="none" />

打字稿:

import { Observable } from 'data/observable';
import * as imagepicker from "nativescript-imagepicker";

var counter = 0;
var fs = require('file-system');

export class AssistenceViewModel extends Observable {

    thumb:any;

public addImage(){
    dialogs.action({
        message: "Opções", 
        cancelButtonText: "Cancelar", 
        actions: ["Câmera", "Galeria"]
    }).then(result => {

        console.log("Dialog result: " + result);
        if(result == "Câmera"){

            //Do action1
            console.log("Abrir camera");

        }else if(result == "Galeria"){

            console.log("Abrir galeria");
            let context = imagepicker.create({
                mode: "single"
            });

            context.authorize().then(function() {
                return context.present();
            }).then(function(selection) {

                selection.forEach(function(selected){

                    selected.getImage().then(function(imagesource){

                        var localPath = null;

                        if(platformModule.device.os === "Android"){
                            localPath = selected.android;
                            console.log("localPath android: " +localPath);
                        }else {
                            // selected_item.ios for iOS is PHAsset and not path - so we are creating own path
                            let folder = fs.knownFolders.documents();
                            let path = fs.path.join(folder.path, "Test" + counter + ".png");
                            let saved = imagesource.saveToFile(path, "png");

                            localPath = path;
                            console.log("localPath iOS: " +localPath);
                        }

                        if(localPath){
                            this.thumb = localPath  // this is not working
                            console.log("thumb: "+this.thumb); // this is not working
                        }

                    });

                });                 

            }).catch(function(e) {
                console.log(e);
            });
        }
    });
  }
}

console.log的结果(“localPath android:”+ localPath);

localPath android: /storage/emulated/0/DCIM/Camera/IMG_20171213_224917038.jpg

但我无法获取 this.thumb 的任何日志。

1 个答案:

答案 0 :(得分:0)

您应该使用TS arrow functions来保留"cache the meaning of this"

的上下文

e.g。用于箭头功能 //这行以上的更多代码

.then(() => {
                return context.present();
            }).then((selection) => {

                selection.forEach((selected) => {

                    selected.getImage().then((imagesource) => {

that = this;模式

var that = this;
// ... your code in the promises follows
that.thumb = newValue;