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

} });

相关内容

热门资讯

解密关于!HH平台挂,hhpo... 解密关于!HH平台挂,hhpoker到底可以作弊码,真是真的是有挂(有挂方法)1、解密关于!HH平台...
三分钟了解!拱趴大菠萝怎么开挂... 三分钟了解!拱趴大菠萝怎么开挂,epoker透视底牌,竟然存在有挂(有挂总结)1、三分钟了解!拱趴大...
一分钟揭秘!aapoker能控... 您好,这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很多玩家在这款游戏中打...
推荐一款!htx矩阵wepok... 推荐一款!htx矩阵wepoker辅助,德州之星扫描器,竟然真的有挂(有挂透明挂);进入游戏-大厅左...
热门推荐!德普之星app安卓版... 热门推荐!德普之星app安卓版破解版,pokemmo辅助脚本,竟然是真的有挂(讲解有挂)1、金币登录...
查到实测辅助!wejoker手... 查到实测辅助!wejoker手机版透视脚本,wepoker透视脚本安卓,确实是真的有挂(有挂秘诀);...
总算了解!wepoker养号规... 总算了解!wepoker养号规律,wepoker透视脚本是什么,好像真的有挂(讲解有挂)1、下载好透...
带你了解!wepoker破解游... 带你了解!wepoker破解游戏盒子,wepoker透视脚本免费,都是真的是有挂(今日头条)能透视中...
免费测试版!hhpoker的辅... 免费测试版!hhpoker的辅助是真的吗,哈糖大菠萝挂,原来存在有挂(有挂功能)所有人都在同一条线上...
今日公布!拱趴大菠萝挂,hhp... 今日公布!拱趴大菠萝挂,hhpoker作弊码,其实有挂(有挂方法)1、金币登录送、破产送、升级送、活...