現在ログインしているユーザーに基づいて一部のページ要素が読み込まれる会社ページを設計しています。たとえば、ある企業がアプリケーションにログインし、ダッシュボードでアカウントの詳細を表示する場合、ダッシュボードページにはその会社の特定の要素(名前、説明など)が読み込まれます。 私の問題は、ページをロードするときに自分のデータが私のVM変数にバインドされないということです。しかし、コンソールをチェックすると、ちょっと後で私のデータが実際にサービスによって取得されていることがわかります。ここで私はそれを考え出した方法は次のとおりです。AngularJSを使用した非同期データの取得
(function() {
'use strict';
angular.module('mainApp')
.controller('currentCompanyCtrl',CurrentCompanyController);
CurrentCompanyController.$inject = ['CompanyService','AlertService', 'AuthService','$routeParams','$http'];
function CurrentCompanyController(CompanyService, AlertService, AuthService, $routeParams) {
var vm = this;
console.log(vm.company); //returns undefined
vm.internships = getInternshipsByLoggedId();
vm.company = getCompanyByLoggedId();
console.log(vm); //returns two undefined objects
for(var x in vm){
console.log(x);
}
//todo find out why vm doesn't get filled earlier, probably has to do with asynchronous calls
//do I need to return a Promise??
//this returns the current company with the id provided by the current logged company
//and binds it to the vm.company object
function getCompanyByLoggedId() {
AuthService.getCompany().then(
function(response) {
CompanyService.getCompanyById(response.data.id).then(
function success(response) {
vm.company = response.data;
console.log(response.data); //this returns the company
},
function error(response) {
vm.serverErrors = response.data;
AlertService.alertError(response.data);
});
});
}
....
後に表示されたビットは、私は私のgetCompanyByLoggedId関数内で行うにconsole.logです。
これは、サービスでデータ検索が非同期に処理されていることと、私がGoogleから読んだり収集できることからプロミスを返さなければならないことを意味します。 私は角度から$ qを使ってみましたが、役に立たなかった。私は私のサービスを変更する必要がありますか?現在、彼らはそうです:
(function() {
'use strict';
angular.module('mainApp')
.factory('AuthService', AuthService);
AuthService.$inject = ['$http'];
function AuthService($http) {
var service = {};
service.getUser = getUser;
service.getStudent = getStudent;
service.getCompany = getCompany;
return service;
function getUser() {
return $http.post('/api/user');
}
function getStudent() {
return $http.post('/api/student');
}
function getCompany() {
return $http.post('/api/company');
}
}
})();
そして
(function() {
'use strict';
angular.module('mainApp')
.factory('CompanyService', CompanyService);
CompanyService.$inject = ['$http'];
function CompanyService($http) {
var service = {};
service.getCompanyById = getCompanyById;
service.getById = getById;
return service;
function getCompanyById(id) {
return $http.get('api/companies/'+id);
}
function getById(id) {
return $http.get('api/companies/'+id+'/internships');
}
}
})();
だから、基本的に私は私のページに表示することができますので、私のVMオブジェクトにデータをバインドすることができるようにしたいです。データが後で到着する場合はどうすればいいですか?
1つの要求から始めます。 –