【问题标题】:Calling a method in the component from a Javascript - Angular2从 Javascript 调用组件中的方法 - Angular2
【发布时间】:2017-05-22 11:03:22
【问题描述】:

我需要从我在同一个组件的构造函数中编写的 Javascript 调用在我的 Angular 组件中声明的方法。我的目标是检测文件输入字段的变化并通过服务将文件上传到服务器。

我在导入之后添加了这个声明。

declare var $: any;

在我的构造函数中,我编写了以下代码。

$(document.body).on("change.bs.fileinput", ".fileinput-exists", function () {

    console.log($(this).parent().find('.myImage').val());
    let input = $(this).parent().find('.myImage');
    this._photoToBeSaved = input.prop('files')[0];
    console.log("my file = " + this._photoToBeSaved);
    //upload the image
    () => {
        this.uploadPhoto(this._photoToBeSaved);
    }
});

以下是同一组件中的uploadPhoto 方法。

uploadPhoto(photo: any) {
    console.log("here i am at upload method);
    // call service method to upload
    .....
}

但是,这不起作用。

请注意,对于构造函数中的以下部分,我遵循了this 问题的答案。我真的可以这样做吗。对吗?

() => {
   this.uploadPhoto(this._photoToBeSaved);
}

uploadPhoto() 方法不会被调用。这是为什么?如何纠正这个问题?

【问题讨论】:

    标签: javascript jquery angular typescript


    【解决方案1】:

    找到了解决办法。把它贴在这里,以便它可以帮助有需要的人。

    我不知道为什么我在问题中提出的方式没有调用Angular2组件中的方法。要走的路是箭头函数

    $(document.body).on("change.bs.fileinput", ".fileinput-exists", (event: Event) => {
        alert("fired");
        let photoToSave = $(event.currentTarget).parent().find('.myImage').val();
        this.uploadPhoto(photoToSave);
    });
    

    uploadPhoto() 方法现在可以正常调用了。

    【讨论】:

    • $('.fileinput-preview img').get(0).src;
    【解决方案2】:

    所以你的目标是检测文件输入的变化并上传它!使用 angularjs 进行操作。 检测角度变化有两个内置功能: $scope.$watchng-change。 不过你可以在这里使用$scope.watch

    html:

     <input ng-model="value" type="file">
    

    角度

     //whenever input value will change will automatically updated here
      $scope.value = '';
     //and when $scope.value will change it will trigger this function
     $scope.$watch = function('value' function(){
         //upload code here
     });
    

    【讨论】:

    • 你能详细说明一下吗?我很难理解这一点
    • 每当文件上传到输入字段时,我都会触发 Jquery 函数。我遇到的问题是无法从 Jquery 调用组件类中的上传函数。我想我会在你的回答中面临同样的问题。不是吗?
    • 肯定会触发$scope.$watch里面的uploadPhoto(element)。现在由您决定。
    • 这就是我的问题所在。方法没有被调用
    猜你喜欢
    • 2017-05-10
    • 1970-01-01
    • 1970-01-01
    • 2017-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多