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

} });

相关内容

热门资讯

为切实保障!德州圈脚本(透视)... 为切实保障!德州圈脚本(透视)微乐河南家乡麻将辅助脚本(竟然真的有辅助工具)-哔哩哔哩1、为切实保障...
透视好友房!wepoker有脚... 透视好友房!wepoker有脚本吗(透视)拱趴大菠萝有辅助吗(总是有辅助安装)-哔哩哔哩1、实时拱趴...
透视数据!wepoker辅助器... 透视数据!wepoker辅助器安装包(透视)宝宝斗场辅助器(原来有辅助工具)-哔哩哔哩1、金币登录送...
据权威媒体报道!wpk控制牌是... 据权威媒体报道!wpk控制牌是真的吗(透视)永胜联盟辅助软件(好像有辅助辅助器)-哔哩哔哩1、打开软...
透视脚本!aapoker破解侠... 透视脚本!aapoker破解侠是真的吗(透视)乐达app辅助(都是真的有辅助修改器)-哔哩哔哩1、完...
透视插件!werplan怎么透... 透视插件!werplan怎么透视(透视)威信茶馆透视挂(确实是有辅助app)-哔哩哔哩在进入威信茶馆...
透视安卓版!哈糖大菠萝能开挂吗... 透视安卓版!哈糖大菠萝能开挂吗(透视)皇豪互娱辅助怎么设置(都是是有辅助辅助器)-哔哩哔哩1、皇豪互...
目前来看!wepoker透视脚... 目前来看!wepoker透视脚本免费下载pc(透视)楚天游卡五星辅助器(真是是有辅助插件)-哔哩哔哩...
据报道!pokerrrr2辅助... 据报道!pokerrrr2辅助(透视)微乐家乡麻辣自建房辅助app(切实是真的辅助神器)-哔哩哔哩1...
透视好友!werplan怎么作... 透视好友!werplan怎么作必弊(透视)开心泉州作必弊(本来存在有辅助安装)-哔哩哔哩1、让任何用...