所以我有一个具有一些功能的Angular工厂。 我想要做的是使用myService来获取数据,并在成功之后调用另一个属于工厂的函数:
myApp.factory('myFactory', function($http) {
return {
myFunction: function() {
MyService.getData().then(
function(response) {
var something = response;
this.anotherFunction(something); //returns undefined
},
function (error) {
//something terrible happened
}
);
},
anotherFunction: function(something) {
console.log(something) //will not run
}
}
});
失败,因为this.anotherFunction
返回undefined
答案 0 :(得分:1)
这是范围问题 - @Component({
selector: 'app',
template: `<textarea placeholder="TextArea" #text (change)="mymodel = text.value" [value]='mymodel'></textarea> <br><br>
{{mymodel}}
`
})
class App {
public mymodel: any = "hello world";
constructor() {}
}
未引用您正在使用它的地方的功能。尝试:
this
现在我们将myApp.factory('myFactory', function($http) {
var factory ={}
factory.anotherFunction = function(something) {
console.log(something) //will not run
}
factory.myFunction = function() {
MyService.getData().then(
function(response) {
var something = response;
factory.anotherFunction(something);
},
function (error) {
//something terrible happened
}
);
}
return factory;
});
初始化为对象,为其分配函数并返回它。这意味着您应该能够从第一个函数中引用factory
。虽然我已经重新订购了它们,因为我不完全确定吊装是否适用于这种方法 - 但我可能错了。
答案 1 :(得分:0)
除了@millerbr提供的解决方案,它完全正常,我发现使用var = this;变量也解决了这个问题:
myApp.factory('myFactory', function($http) {
return {
var that = this;
myFunction: function() {
MyService.getData().then(
function(response) {
var something = response;
that.anotherFunction(something); //returns undefined
},
function (error) {
//something terrible happened
}
);
},
anotherFunction: function(something) {
console.log(something) //will not run
}
}
});
答案 2 :(得分:-2)
你必须像这样写
myApp.factory('myFactory', function($http) {
var self{};
self.anotherFunction = function(something) {
console.log(something) //will not run
} ;
self.myFunction = function() {
MyService.getData().then(
function(response) {
var something = response;
self.anotherFunction(something); //returns undefined
},
function (error) {
//something terrible happened
}
};
return self;
});