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();

} });

相关内容

热门资讯

透视透视"陕麻圈黑科... 透视透视"陕麻圈黑科技"开挂(透视)wepoker可以开透视吗(竟然有挂);一、陕麻圈黑科技有挂的是...
揭秘"丽水都莱大菠萝... 揭秘"丽水都莱大菠萝脚本辅助"开挂(透视)拱趴大菠萝十三水作弊(有挂方针);详细丽水都莱大菠萝脚本辅...
重大通报"大唐山西辅... 重大通报"大唐山西辅助"开挂(透视)hhpoker透视方法(有挂详情)hhpoker透视方法ai黑科...
2分钟细说"中至上饶... 2分钟细说"中至上饶打炸漏洞"开挂(透视)wepoker怎么看底牌(有挂方针)【无需打开直接搜索加薇...
透视工具"摸一把游戏... 您好:这款摸一把游戏跑得快辅助游戏是可以开挂的,确实是有挂的,很多玩家在这款摸一把游戏跑得快辅助游戏...
必备辅助推荐"陕西三... 必备辅助推荐"陕西三代辅助"开挂(透视)wpk透视插件(有挂总结);无需打开直接搜索加(薇:1367...
玩家必备攻略"hhp... 玩家必备攻略"hhpoker是正规平台吗"开挂(透视)约局吧作弊脚本(有挂方针);打开点击测试直接进...
总算了解"传送屋ap... 总算了解"传送屋app辅助脚本下载"开挂(透视)wepoker透视方法(有挂分析);打开点击测试直接...
揭秘一下"五十k辅助... 您好:这款wepoker软件辅助程序游戏是可以开挂的,确实是有挂的,很多玩家在这款wepoker软件...
玩家科普"新财神正版... 玩家科普"新财神正版辅助挂"开挂(透视)约局吧德州透视(有挂技巧) 【无需打开直接搜索加薇13670...