我正在使用角度应用程序,我有以下功能。
功能1
vm.getDetails = function () {
var infoKey = "INFO2";
var url = "www.example.com" + InfoKey;
return datacontext.getData(url)
.then(function (response) {
return vm.detailsResponse = response.data.texts;
});
}
vm.getDetails();
功能2
//Text button
@IBOutlet weak var TextLabel: UILabel!
@IBAction func TextButtonTapped(_ sender: UIButton) {
print("Text Button Tapped")
openTextAlert()
}
func openTextAlert() {
//Create Alert Controller
let alert9 = UIAlertController (title: "Whatever Text Your Heart Desires:", message: nil, preferredStyle: UIAlertControllerStyle.alert)
//Create Cancel Action
let cancel9 = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: nil)
alert9.addAction(cancel9)
//Create OK Action
let ok9 = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) { (action: UIAlertAction) in print("OK")
let textfield = alert9.textFields?[0]
print(textfield?.text!)
self.TextLabel.text = textfield?.text!
}
alert9.addAction(ok9)
//Add Text Field
alert9.addTextField { (textfield: UITextField) in
textfield.placeholder = "Whatever text you want to enter"
}
//Present Alert Controller
self.present(alert9, animated:true, completion: nil)
}
上述两个函数都有类似的行为,但只有 infoKey 和返回值发生了变化。现在我已经写了这样的功能。这可能听起来很愚蠢,但我如何优化此功能以减少代码冗余。
答案 0 :(得分:0)
创建一个接受infoKey的公共函数,然后仅在回调函数中返回response.data.texts和Handel VM变量。
答案 1 :(得分:0)
您可以尝试以下方法 -
1)获取infoKey
作为参数&返回response.data.texts
-
function get(infoKey) {
var url = "www.example.com" + InfoKey;
return datacontext.getData(url)
.then(function (response) {
return response.data.texts;
});
}
2)将可调用函数作为参数传递以处理响应 -
function get(infoKey, handleResponse) {
var url = "www.example.com" + InfoKey;
return datacontext.getData(url)
.then(handleResponse);
}
像这样使用它 -
get('Infokey1', function onResponse(response) {
vm.infoResponse = response.data.texts;
})
答案 2 :(得分:0)
function getInfo(infoKey) {
var url = "www.example.com" + infoKey;
var promise = datacontext.getData(url);
return promise;
}
调用函数应该执行以下操作:
getInfo(infoKey).then((response)=> {
vm.detailsResponse = response.data.texts;
},(err)=>{
//Handle errors here.
});
或者,你可以简单地向getInfo函数发送一个回调并在那里处理它。
答案 3 :(得分:0)
vm.getDetails = function (infoKey) {
var url = "www.example.com" + infoKey;
return datacontext.getData(url)
.then(function (response) {
if(infoKey=="INFO1"){return vm.infoResponse = response.data.texts;}
else{ return vm.detailsResponse = response.data.texts;}
});
}
vm.getDetails(infoKey);
希望这对你有所帮助。