【发布时间】:2019-10-19 19:13:47
【问题描述】:
我的代码的某些部分随机出现问题。
此对象在angular controller 中声明。
this.tData = {
'questions':[],
'typeQuestion':[],
'category':[],
'dName':this.dName,
'tCodigo':this.tCodigo}
然后我从其他函数中获取了一些数据并将其推送到相应的字段中,
this.tData.questions.push(this.idQuestion) // this come from frontend ng-model
this.tData.typeQuestion.push(this.typeQuest) // this come from frontend ng-model
this.tData.category.push(this.idCategory)// this come from frontend ng-model
这很好地构造了我的对象。做console.log(this.tData) 向我展示完全没问题的对象。但是当我在angular service 的这个函数中将它传递给后端时。
this.updateStuff = function(codStuff,tData){
return $http.put('/updateStuff' + codStuff,tData)}
后端得到的对象console.log(params)是
{
questions:['exampleId'],
typeQuestion:['exampleData'],
category:[], // HERE IS THE PROBLEM
dName:'exampleName',
tCodigo:'exampleCod'}
就像你看到的category:[] 是空的,但是在我发送之前在angular 的服务中执行console.log(tData),我在那里看到了正确的数据。
当我将数据发送到后端时,我错过了数据。这个问题在其他 3 个类似的案例中发生在我身上。
为什么有些数组在后端可以正常使用,而有些则不行?
我尝试了很多东西,但我发送到后端的对象中有一项是空的。
如果您需要更具体的代码,请在 cmets 中告诉我。
更新
这里的代码我在控制器中推送类别:
this.getCategoryByName = function(){
this.bName = document.getElementById('seCategory').value;
Category.getCategoryByName(this.bName).then((result)=>{
this.idCategory = result.data.data._id; // this give me id of category
this.tData.category.push(this.idCategory);
})
}
2
这是我在前端调用函数的地方:
<button class="btn btn-primary" ng-click="ctController.getCategoryByName(); ctController.updateTest();" > up </button>
这是updateTest()函数的代码:
this.updateTest = function(){
Test.updateTest(this.codTest,this.tData).then(result=>{})
}
上面的方法调用angular serviceupdateStuff
已解决
解决了在方法 getCategoryByName 中添加链式 promise 并添加嵌套在 getCategoryByName() 方法中的 updateTest() 方法,或多或少类似于 @T.J. Crowder 建议,所以我给出了回应。
【问题讨论】:
-
见this question's answers。不要用
console.log手电筒在黑暗中跌跌撞撞,请使用浏览器和/或 IDE 中内置的调试器打开灯。在调用this.updateStuff时设置断点。当断点被命中时,查看this.tData.category。您几乎肯定会看到它是空的。 -
好建议(我将使用调试器),我添加了一个断点 int $http.put 但仍然看到完整的对象。
-
但那是后端说
category为空的时候吗? 那就是你需要抓住的情况。我很确定$http.put没有损坏,所以要么 A) 你传递的内容在category中没有任何内容,要么 B) 你的后端代码弄乱了它收到的内容。 -
我认为后端不是问题。我使用邮递员对其进行了测试,一切正常,所以问题出在前端。但还是不能解决问题,要调试所有方法。
-
请用minimal reproducible example 更新您的问题,证明问题,最好是可运行 使用堆栈片段(
[<>]工具栏按钮;details)。代替return $http.put('/updateStuff' + codStuff,tData)},您可以使用console.log(JSON.stringify(tData));来捕获调用updateStuff时tData中的内容。我认为如果没有一个,我们无法为您提供更多帮助。 (就我自己而言,我确信updateStuff就是still being called beforegetCategoryByNameis done。)祝你好运!
标签: javascript angularjs object