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

} });

相关内容

热门资讯

透视app!hhpoker辅助... 透视app!hhpoker辅助实战视频,wepoker透视功能下载,法子教程(切实有挂)-哔哩哔哩一...
透视输赢!约局吧是否有挂(透视... 透视输赢!约局吧是否有挂(透视)开挂辅助软件(其实是有挂)-哔哩哔哩约局吧是否有挂辅助器中分为三种模...
透视代打!来玩德州破解器,we... 透视代打!来玩德州破解器,we-poker辅助器,手册教程(总是真的有挂)-哔哩哔哩1、来玩德州破解...
透视辅助挂!拱趴大菠萝万能辅助... 透视辅助挂!拱趴大菠萝万能辅助器(透视)开挂辅助脚本(一贯是真的挂)-哔哩哔哩1、拱趴大菠萝万能辅助...
透视挂!wpk有那种辅助吗(透... 透视挂!wpk有那种辅助吗(透视)开挂辅助攻略(本来有挂)-哔哩哔哩1、下载好wpk有那种辅助吗辅助...
透视科技!德普之星辅助器app... 透视科技!德普之星辅助器app,aa poker透视软件,技法教程(一贯是有挂)-哔哩哔哩1、操作简...
透视存在!竞技联盟辅助(透视)... 透视存在!竞技联盟辅助(透视)开挂辅助app(本来是有挂)-哔哩哔哩1、每一步都需要思考,不同水平的...
透视脚本!德普之星透视辅助,h... 透视脚本!德普之星透视辅助,hhpoker软件可以玩吗,绝活儿教程(原来是真的挂)-哔哩哔哩hhpo...
透视代码!aapoker透视怎... 透视代码!aapoker透视怎么用(透视)开挂辅助插件(果然是有挂)-哔哩哔哩1、玩家可以在aapo...
透视工具!aapoker破解侠... 透视工具!aapoker破解侠是真的吗,wepoker私人局怎么玩,方案教程(一贯存在有挂)-哔哩哔...