1 javascript angularjs angular-promise
我有这个问题使用解决方案与组件和ui-router,解决后承诺的数据"未定义"在控制器中
服务:
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);
}
)
}
Run Code Online (Sandbox Code Playgroud)
模块/组件/路由:
.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();
}
}
});
})
Run Code Online (Sandbox Code Playgroud)
控制器:
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;
Run Code Online (Sandbox Code Playgroud)
注入控制器后,对象在"http"调用后通过promise"解决"
this.userdata = userdata;
this.accdata = accdata;
Run Code Online (Sandbox Code Playgroud)
未定义!!!
哪里是虫子.??
非常感谢...
将getCollaboratores函数更改为:
getCollaboratores () {
return this.$http.get(this.API_URL + '/collaboratores').then(
(resolve) => { // promise resolve
console.log('Success',resolve.data);
return resolve;
});
}
Run Code Online (Sandbox Code Playgroud)
与其他一个getAccount一样(即在成功回调返回解析内).
这将解决您的问题.
原因是,一旦你链接成功回调,第一回调就返回可以作为第二回调的参数的东西.由于服务中的成功回调没有返回任何内容(js中函数的默认返回值未定义),因此控制器中没有可用的解析值.
| 归档时间: |
|
| 查看次数: |
900 次 |
| 最近记录: |