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

} });

相关内容

热门资讯

透视曝光"We po... 透视曝光"We poker辅助器下载"总是是有辅助软件(哔哩哔哩)进入游戏-大厅左侧-新手福利-激活...
透视详细"聚星ai辅... 透视详细"聚星ai辅助工具激活码"确实真的有辅助app(哔哩哔哩)1)聚星ai辅助工具激活码辅助插件...
透视科普"红龙pok... 透视科普"红龙poker辅助器免费观看"其实真的是有辅助挂(哔哩哔哩)在进入红龙poker辅助器免费...
透视详情"wepok... 透视详情"wepoker辅助器官方"切实是真的辅助软件(哔哩哔哩)1.wepoker辅助器官方 选牌...
透视辅助"拱趴游戏破... 透视辅助"拱趴游戏破解器"本来真的是有辅助神器(哔哩哔哩)拱趴游戏破解器辅助器是一种具有地方特色的麻...
透视了解"竞技联盟透... 透视了解"竞技联盟透视"都是是真的辅助软件(哔哩哔哩)1、任何竞技联盟透视透视是真的假的的玩家都可以...
透视揭露"wepok... 透视揭露"wepoker破解游戏盒子"好像是有辅助工具(哔哩哔哩)1、玩家可以在wepoker破解游...
透视开挂"哈糖大菠萝... 透视开挂"哈糖大菠萝辅助器"都是有辅助神器(哔哩哔哩)1、哈糖大菠萝辅助器辅助软件下载优化,哈糖大菠...
透视揭幕"hhpok... 透视揭幕"hhpoker有没有作必弊辅助"总是存在有辅助技巧(哔哩哔哩)1、不需要AI权限,帮助你快...
透视有挂"德扑圈透视... 透视有挂"德扑圈透视挂"一直是有辅助app(哔哩哔哩)1.德扑圈透视挂 选牌创建新账号,点击进入游戏...