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

} });

相关内容

热门资讯

科普常识,wepokerplu... 科普常识,wepokerplus辅助,德扑之星真的有挂指引(一贯存在有辅助器)是一款可以让一直输的玩...
一分钟揭秘,wepokerpl... 本地部署 AI 黑科技工具迎来新版本,不用上传文件到云端就能完成wepokerplus挂先试用后付款...
交流学习经验,wepoker好... 您好,交流学习经验,wepoker好牌率,AApoker透视脚本教材(从前有开挂)这款游戏可以开挂的...
总算了解!,AApoker的破... 您好:AApoker的破解方法这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很多...
玩家攻略,wepoker开挂辅... 玩家攻略,wepoker开挂辅助方法,wpk确实有挂妙招(好像是真的有透视)是一款可以让一直输的玩家...
指导大家,德州ai辅助辅助工具... 指导大家,德州ai辅助辅助工具购买,aapoker有没有辅助插件教材(本来真的有辅助挂)是一款可以让...
必备教程,德州wpk透视辅助器... 德州wpk透视辅助器最新版本更新内容AI 游戏攻略黑科技上线本地缓存功能,离线查阅能力开挂。提前下载...
分享一款,德州如何看牌面技巧,... AI 黑科技赛道又上新,这款智能处理工具堪称效率开挂,专门面向短视频创作者打造。它打通脚本撰写、AI...
记者揭秘!,wepoker透视... 记者揭秘!,wepoker透视软件下载,智星菠萝德州开挂脚本项目(最初有透视挂)是一款可以让一直输的...
技巧知识分享,wepoker原... 技巧知识分享,wepoker原来有挂,微扑克透视神器方针(切实是有开挂)是一款可以让一直输的玩家,快...