1

私はこのようなプロミスチェーンを持っています...

this.getFile(fileId).then(updateFile).then(displayAllDoneMessage);

wheregetFile()updateFile()each を使用ngResourceして適切な JSON 呼び出しを作成し、$resource.$promise.

$scopeチェーンは正常に起動しますが、内部からのアクセスに問題がありますupdateFile

だからgetFile()私は持っています

// this works
this.status.text = "fetching file"

しかし、updateFile()私は持っています

// this fails at runtime because "this" is not $scope
this.status.text = "updating file"

私は何を間違っていますか、または$scope内で利用できるようにするために何をする必要がありますupdateFile()か?

重要な場合に備えて、TypeScript を使用していることを追加する必要があります。

4

2 に答える 2

3

TypeScript を使用していて、ポインターを維持したいthis場合は、ラムダ構文を使用していることを確認する必要があります。

$scope次のように、コンストラクターでプライベート/パブリック変数としてオフに保存したと仮定します。

constructor(private $scope){ /* snip */ }

$scope次に、これを行うだけで、好きなものにアクセスしていることを確認できます。

this.getFile(fileid)
.then((result) => {
   return this.$scope.updateFile(result);
})
.then((result) => {
   return this.$scope.displayAllDoneMessage(result);
});

内部的には、これは次のようなものにコンパイルされます。

//Save 'this' off to a closure
var _this = this;

_this.getFile(fileid)
.then(function(result){
   return _this.$scope.updateFile(result);
})
.then(function(result){
   return _this.$scope.displayAllDoneMessage(result);
});

TypeScipt は、クロージャを使用して、への適切な参照を維持します。this

于 2014-01-31T13:08:43.743 に答える
0

を呼び出すthis.getFileと、コンテキストはになります。あなたの場合は $scope オブジェクトthisだと思いますので、内部は $scope です。thisthisgetFile

ただしupdateFiledisplayAllDoneMessageフレームワークによってコールバックとして呼び出されthis、$scope を参照しなくなります。

$scope をコンテキストとしてバインドするには、.bindを試してください。

this.getFile(fileId).then(updateFile.bind(this)).then(displayAllDoneMessage.bind(this));

古いブラウザーの場合、このスクリプトをポリフィルとして含めることができます (ドキュメントから引用)。

if (!Function.prototype.bind) {
  Function.prototype.bind = function (oThis) {
    if (typeof this !== "function") {
      // closest thing possible to the ECMAScript 5 internal IsCallable function
      throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
    }

    var aArgs = Array.prototype.slice.call(arguments, 1), 
        fToBind = this, 
        fNOP = function () {},
        fBound = function () {
          return fToBind.apply(this instanceof fNOP && oThis
                                 ? this
                                 : oThis,
                               aArgs.concat(Array.prototype.slice.call(arguments)));
        };

    fNOP.prototype = this.prototype;
    fBound.prototype = new fNOP();

    return fBound;
  };
}
于 2014-01-31T13:06:53.050 に答える