组件:ui-router resolve不会注入控制器,数据未定义 [英] Component : ui-router resolve will not inject into controller, data undefined
问题描述
我有使用resolve with component& amp; ui-router,解决后承诺中的数据在控制器中是未定义的
I have this problem using resolve with component & ui-router, the data "after" resolving promise are "undefined" in a controller
服务:
class userService {
constructor ($http, ConfigService, authService) {
this.$http = $http;
this.API_URL = `${ConfigService.apiBase}`;
this.authService = authService;
}
testAuth () {
return this.$http.get(this.API_URL + '/test-auth')
}
getCollaboratores () {
return this.$http.get(this.API_URL + '/collaboratores').then(
(resolve) => { // promise resolve
console.log('Success',resolve.data);
}
)
}
getAccount () {
var config = {
headers: { "X-Shark-CollaboratoreId" : "1"}
};
return this.$http.get(this.API_URL + '/accounts' + '/' + 1, config).then(
(resolve) => { // promise resolve
console.log('Success',resolve.data);
}
)
}
模块/组件/路由:
.config(($stateProvider, $urlRouterProvider) => {
"ngInject";
$urlRouterProvider.otherwise('/');
$stateProvider
.state('core', {
redirectTo: 'dashboard',
url: '/core',
component: 'core',
resolve: {
userdata: (userService) => {
return userService.getCollaboratores();
},
accdata: (userService) => {
return userService.getAccount();
}
}
});
})
控制人:
let self;
class CoreController {
constructor($state,userService,authService,userdata,accdata) {
this.name = 'core';
this.$state = $state;
this.userService = userService;
this.authService = authService;
this.userdata = userdata;
this.accdata = accdata;
console.log('name',this.name);
self = this;
console.log('userdata',self);
}
}
CoreController.$inject = ['$state','userService', 'authService','userdata','accdata'];
export default CoreController;
注入控制器后,http调用后对象已解决
After injecting in the controller the object "resolved" by promise after "http" call
this.userdata = userdata;
this.accdata = accdata;
未定义!!!
其中是错误。??
非常感谢...
推荐答案
将getCollaboratores函数更改为:
Change the getCollaboratores function to below :
getCollaboratores () {
return this.$http.get(this.API_URL + '/collaboratores').then(
(resolve) => { // promise resolve
console.log('Success',resolve.data);
return resolve;
});
}
对其他一个getAccount做同样的事情(即在成功回调中返回解析) 。
Do the same with other one getAccount (i.e inside the success callback return resolve).
这将解决您的问题。
原因是一旦你链接成功回调,第一回调就是返回可以作为第二回调的参数的东西。由于服务中的成功回调没有返回任何内容(js中函数的默认返回值未定义),因此控制器中没有可用的解析值。
Reason is once you chain success callbacks, 1st callback as to return the something which can be the arguments for the 2nd callback. Since the success callback in service was not returning anything(default return value of a function in js is undefined), hence resolved value was not available in the controller.
这篇关于组件:ui-router resolve不会注入控制器,数据未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!