我在使用组件和 ui-router 的 resolve 时遇到了这个问题,“在”resolving promise 之后的数据在 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();
}
}
});
})
Controller :
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;
在 Controller 中注入(inject)“http”调用后由 promise“解析”的对象
this.userdata = userdata;
this.accdata = accdata;
未定义!!!
bug在哪里??
非常感谢...
最佳答案
将 getCollaboratores 函数更改为以下:
getCollaboratores () {
return this.$http.get(this.API_URL + '/collaboratores').then(
(resolve) => { // promise resolve
console.log('Success',resolve.data);
return resolve;
});
}
对另一个 getAccount 做同样的事情(即在成功回调返回解析中)。
这将解决您的问题。
原因是一旦你链接成功回调,第一个回调返回可以作为第二个回调参数的东西。由于服务中的成功回调未返回任何内容(js 中函数的默认返回值未定义),因此解析值在 Controller 中不可用。
关于javascript - 组件 : ui-router resolve will not inject into controller, 数据未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42395143/