AngularJS异步问题如何从另一个组件中加载数据?
创始人
2024-10-27 13:30:17
0

在AngularJS项目中,可以通过以下两种方法从另一个组件中加载数据:

  1. 使用服务: 创建一个服务,用于在不同的组件之间共享数据。在需要加载数据的组件中注入这个服务,并调用其方法获取数据。

// Service angular.module('myApp').service('dataService', function($http) { var data = {};

this.getData = function() { return $http.get('/api/data').then(function(response) { data = response.data; }); };

this.getDataInService = function() { return data; }; });

// Component A angular.module('myApp').component('componentA', { templateUrl: 'componentA.html', controller: function(dataService) { var ctrl = this;

ctrl.$onInit = function() {
  dataService.getData().then(function() {
    ctrl.data = dataService.getDataInService();
  });
};

} });

// Component B angular.module('myApp').component('componentB', { templateUrl: 'componentB.html', controller: function(dataService) { var ctrl = this;

ctrl.data = {};

dataService.getData().then(function() {
  ctrl.data = dataService.getDataInService();
});

} });

  1. 使用事件广播: 在加载数据的组件中,使用$scope.$broadcast()方法广播一个事件,另一个组件可以通过$scope.$on()方法监听这个事件并获取数据。

// Component A angular.module('myApp').component('componentA', { templateUrl: 'componentA.html', controller: function($scope) { var ctrl = this;

$scope.$on('dataLoaded', function(event, data) {
  ctrl.data = data;
});

} });

// Component B angular.module('myApp').component('componentB', { templateUrl: 'componentB.html', controller: function($http, $scope) { var ctrl = this;

ctrl.loadData = function() {
  $http.get('/api/data').then(function(response) {
    $scope.$broadcast('dataLoaded', response.data);
  });
};

ctrl.loadData();

} });

相关内容

热门资讯

透视详情!德普之星透视软件免费... 透视详情!德普之星透视软件免费入口官网,德普辅助器怎么用-确实真的有辅助脚本(哔哩哔哩)1、下载好透...
透视总结!wepoker线上大... 透视总结!wepoker线上大神,wepoker破解工具-一直真的有辅助脚本(哔哩哔哩)进入游戏-大...
透视详情!wepoker透视脚... 透视详情!wepoker透视脚本免费app,wepoker永久免费脚本-一贯存在有辅助神器(哔哩哔哩...
透视解密!wepoker有机器... 透视解密!wepoker有机器人吗,wepoker作弊方法-总是一直总是有辅助软件(哔哩哔哩)1、模...
透视揭露!pokerworld... 透视揭露!pokerworld破解版下载,哈糖大菠萝能开挂吗-果然是有辅助插件(哔哩哔哩);1、首先...
透视教你!德州之星扫描器,来玩... 透视教你!德州之星扫描器,来玩app破解版-一贯是真的有辅助插件(哔哩哔哩)1、德州之星扫描器模拟器...
透视科普!wpk模拟器,wpk... 透视科普!wpk模拟器,wpk系统是否存在作弊行为-本来存在有辅助插件(哔哩哔哩)1、任何透视是真的...
透视详情!wepoker看底牌... 透视详情!wepoker看底牌,wejoker辅助器怎么卖-真是有辅助软件(哔哩哔哩)1、玩家可以在...
透视揭露!佛手在线是不是有挂,... 透视揭露!佛手在线是不是有挂,拱趴大菠萝有什么挂-真是一直都是有辅助技巧(哔哩哔哩)1、完成佛手在线...
透视推荐!hhpoker免费透... 透视推荐!hhpoker免费透视脚本,hhpoker作弊实战视频-原来是真的有辅助软件(哔哩哔哩)1...