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

} });

相关内容

热门资讯

一秒答解!aapoker怎么控... 一秒答解!aapoker怎么控制牌(辅助挂)确实真的有挂(有挂分析辅助脚本)1、上手简单,内置详细流...
科技通报!pokerrrr2辅... 科技通报!pokerrrr2辅助(辅助挂)其实是真的有挂(有挂存在辅助插件)1、打开软件启动之后找到...
盘点一款!wepoker怎么开... 盘点一款!wepoker怎么开辅助(辅助挂)一贯真的有挂(发现有挂辅助攻略);1、下载好脚本下载之后...
玩家实测!we-poker辅助... 玩家实测!we-poker辅助(辅助挂)其实存在有挂(有挂猫腻辅助app)1、许多玩家不知道辅助怎么...
教学盘点!wepoker手机助... 教学盘点!wepoker手机助手(辅助挂)好像是真的有挂(详细教程辅助软件)1、实时透视辅助更新:用...
我来教大家!hhpoker德州... 我来教大家!hhpoker德州牛仔视频(辅助挂)一直有挂(有挂分析辅助app)1、起透看视 辅助软件...
技术分享!hhpoker是正品... 技术分享!hhpoker是正品吗(辅助挂)本来真的是有挂(存在有挂辅助攻略)1、操作简单,无需手机版...
分辨真假!拱趴大菠萝十三水作弊... 分辨真假!拱趴大菠萝十三水作弊(辅助挂)原来存在有挂(有挂教学辅助工具)1、实时透视辅助更新:用户可...
科技通报!aapoker辅助器... 科技通报!aapoker辅助器是真的吗(辅助挂)都是真的是有挂(有挂规律辅助软件)1、每一步都需要思...
新手必备!有没有人wepoke... 您好,这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很多玩家在这款游戏中打...