我有一个服务功能,它返回一个承诺列表:
getData(user) {
return this.$q.all({
userInfo: this.$http.get(this.buildUrl('user.getinfo', user)),
userTopArtists: this.$http.get(this.buildUrl('user.gettopartists', user)),
userChart: this.$http.get(this.buildUrl('user.getWeeklyChartList', user))
}).then(resp => {
return resp;
}).catch(err => {
this.$q.reject('Error' + err.status);
})
}
,我在我的控制器内部打电话:
validateUser() {
this.error = null;
this.service.getData(this.$scope.username)
.then(resp => {
if (resp.userInfo.data.user) {
this.service.storeUserData('userData', JSON.stringify(resp));
this.$location.path('/profile');
} else {
this.error = resp.userInfo.data.message;
}
})
}
到目前为止工作正常,但我正在寻找的是特别操纵我从userChart
请求获得的数据。
我想操纵我从调用userChart
得到的json,将其中的一些存储在一个数组中,并使用初始请求中存储的数组对象值作为参数发出另一个返回数据的请求。
所以基本上我不需要来自userChart
的json,我只需要使用它来使用它的一些数据进行嵌套(?)请求。
答案 0 :(得分:1)
如果从then
返回承诺,原始承诺的调用者将等待嵌套承诺解决。如果调用者是您使用$q.all
或其他内容的服务并不重要,则会将其链接。
这只显示相关代码,它位于您的服务中,其他所有内容都保持不变。
userChart: this.$http.get(this.buildUrl('user.getWeeklyChartList', user))
.then((result) => {
// additional manipulation if needed on result
// second call to http and return the resulting promise
return this.$http.doSomething('');
});
答案 1 :(得分:0)
我还没有尝试过这个,但也许你可以在它回来后立即对该电话的结果做些什么?像这样的东西?
getData(user) {
return this.$q.all({
userInfo: this.$http.get(this.buildUrl('user.getinfo', user)),
userTopArtists: this.$http.get(this.buildUrl('user.gettopartists', user)),
userChart: this.$http.get(this.buildUrl('user.getWeeklyChartList', user)).
then(function(response) {
// Do something with the successful response
}, function(response) {
// Do something for the failed response
})
}).then(resp => {
return resp;
}).catch(err => {
this.$q.reject('Error' + err.status);
})
}
答案 2 :(得分:0)
如果我了解你的需求,你应该首先获得图表响应然后使用该响应来调用其他Web服务,所以这样的事情应该有效:
validateUser() {
this.getData({})
.then(function (response) {
// response containing 'userInfo' and 'userTopArtists'
console.log(arguments);
});
}
getData(user) {
const me = this;
return me.$http.get('https://jsonplaceholder.typicode.com/users')
.then(function (charts) {
return me.$q.all({
// use charts as param for other calls...
userInfo: me.$http.get('https://jsonplaceholder.typicode.com/users'),
userTopArtists: me.$http.get('https://jsonplaceholder.typicode.com/users')
});
})
.catch(err => {
me.$q.reject('Error' + err.status);
});
}