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

} });

相关内容

热门资讯

透视计算!hhpoker德州真... 透视计算!hhpoker德州真的假的(透视)总是有辅助软件(详细教程)-哔哩哔哩该软件可以轻松地帮助...
据公告内容!wepoker安装... 据公告内容!wepoker安装教程(透视)本来真的是有辅助app(有挂详情)-哔哩哔哩wepoker...
透视神器!hhpoker有没有... 透视神器!hhpoker有没有外开挂(透视)好像存在有辅助神器(有挂存在)-哔哩哔哩1)hhpoke...
透视实锤!wepoker怎么破... 透视实锤!wepoker怎么破解游戏(透视)竟然是真的辅助插件(了解有挂)-哔哩哔哩一、wepoke...
透视系统!拱趴大菠萝有什么挂(... 透视系统!拱趴大菠萝有什么挂(透视)果然是真的辅助app(有挂技术)-哔哩哔哩1)拱趴大菠萝有什么挂...
透视有挂!德州透视插件(透视)... 透视有挂!德州透视插件(透视)好像是真的辅助软件(存在有挂)-哔哩哔哩1、德州透视插件脚本辅助下载、...
有玩家发现!hhpoker一直... 有玩家发现!hhpoker一直输有挂吗(透视)确实是有辅助app(确实有挂)-哔哩哔哩1、完成hhp...
随着!wepoker安装教程(... 随着!wepoker安装教程(透视)好像有辅助修改器(讲解有挂)-哔哩哔哩1、超多福利:超高返利,海...
辅助透视!wejoker辅助脚... 辅助透视!wejoker辅助脚本(透视)竟然存在有辅助修改器(确实有挂)-哔哩哔哩1、wejoker...
透视辅助!aapoker破解侠... 透视辅助!aapoker破解侠是真的吗(透视)本来真的有辅助软件(有挂透视)-哔哩哔哩1、这是跨平台...