あなたが持っているとして、あなたがservice
にlogin
を結合し、this
は(login
関数本体で使用している場合)login
の実行中にservice
オブジェクトを参照します。しかし、login
関数内で定義され、引き数として.then()
に渡された後続のコールバックでは、this
はコールバックが実行された時点でサービスオブジェクトを参照しなくなるため、bind
のサービスのために(this
)コールバックするか、クロージャーに格納します。他
// binding 'this' to the service
function login(userName, password, successCallback) {
var requestBody = 'grant_type=password&username=' + userName + '&password=' + password;
$http.post($rootScope.baseUrl + 'token', requestBody)
.then(function (response) {
this.isUserAuthenticated = true;
successCallback(response);
}.bind(this),
function (response) {
console.log(response);
});
}
か:したがって、あなたはlogin
機能書き直すことができ、あなたの場合は
// storing the service as a closure
function login(userName, password, successCallback) {
var requestBody = 'grant_type=password&username=' + userName + '&password=' + password;
var self = this;
$http.post($rootScope.baseUrl + 'token', requestBody)
.then(
function (response) {
self.isUserAuthenticated = true;
successCallback(response);
},
function (response) {
console.log(response);
});
}
をすでに変数としてサービスを保存していることから、後者は、厳密には必要ではないことlogin
関数の外で宣言され、true
をservice.isAuthenticated
に割り当てることができます。あなたはES6、関数リテラルを使用している場合
また、(すなわち、)あなたがfat-矢印表記を使って書くこともでき.then()
にコールバックとして渡している、とバインディングコンテキストが自動的に実行されます。
function login(userName, password, successCallback) {
var requestBody = 'grant_type=password&username=' + userName + '&password=' + password;
$http.post($rootScope.baseUrl + 'token', requestBody)
.then((response) => {
this.isUserAuthenticated = true;
successCallback(response);
},
(response) => {
console.log(response);
});
}
あなたの質問に間違いがあると誤解されるかもしれませんが、成功コールバックservice.isUserAuthenticated = trueの前に行うことはできませんか? – zangarmarsh
確かにあなたは単に設定できませんでした:service.isUserAuthenticated = true – kjonsson
あなたはどの質問をお読みになりましたか?それらをリンクしてください。 – Bergi