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

} });

相关内容

热门资讯

总算明白!wepoker辅助,... 总算明白!wepoker辅助,白金岛跑胡子脚本,详细神器(揭秘有挂)1、金币登录送、破产送、升级送、...
免费测试版!微信小程序微乐辅助... 免费测试版!微信小程序微乐辅助器教程,微乐家乡麻辣自建房辅助app,详细教程(有挂工具)1、很好的工...
记者发布!阿拉斗牌辅助,随意玩... 记者发布!阿拉斗牌辅助,随意玩最新跳转链接有辅助吗,详细工具(有挂教学)1、任何随意玩最新跳转链接有...
玩家必看科普!微乐陕西三代自建... 玩家必看科普!微乐陕西三代自建房挂,广东雀神挂机怎么样,详细软件(有挂技术)微乐陕西三代自建房挂是不...
总算了解!米娱gm游戏辅助工具... 总算了解!米娱gm游戏辅助工具,微乐小程序辅助器,详细脚本(讲解有挂)1、完成米娱gm游戏辅助工具有...
科技通报!新518互游插件,哥... 科技通报!新518互游插件,哥哥打大a外挂,详细神器(有挂猫腻)1、每一步都需要思考,不同水平的挑战...
科技新动态!微信西楚辅助,小程... 科技新动态!微信西楚辅助,小程序跑得快的辅助,详细app(有挂实锤)1、许多玩家不知道小程序跑得快的...
技术分享!免费游戏辅助软件,微... 技术分享!免费游戏辅助软件,微乐智能辅助真的假的,详细神器(有挂实锤)1、该软件可以轻松地帮助玩家将...
发现一款!新畅游插件,微信小程... 发现一款!新畅游插件,微信小程序修改器,详细工具(有挂秘籍)1、微信小程序修改器辅助器安装包、微信小...
9分钟了解!斗城麻将微信有没有... 9分钟了解!斗城麻将微信有没有挂,斗棋有bug么开挂,详细插件(有挂方法)1、上手简单,内置详细流程...