嗨我对How to pass a value from one component to another component Angular 2 (No parent child relationship)提出了同样的问题。我有一个component1,订阅一个服务,它使.get到服务器并从那里获取一个具有很少属性的对象。这是否适合将此对象从component1转移到与该allert方法没有父子关系的独立组件2?
答案 0 :(得分:0)
我会使用服务在两个没有父/子关系的组件之间共享数据。将对象存储在服务中(由Component1触发,听起来像),然后将服务注入Component2并从服务中获取对象。
答案 1 :(得分:0)
在带有发射和广播的Angular 1中,我们实现了更多细节visit
<!DOCTYPE html>
<html>
<head>
<title>Broadcasting</title>
<script src="lib/angular.js"></script>
<script>
var app = angular.module('app', []);
app.controller("firstCtrl", function ($scope) {
$scope.$on('eventName', function (event, args) {
$scope.message = args.message;
console.log($scope.message);
});
});
app.controller("secondCtrl", function ($scope) {
$scope.handleClick = function (msg) {
$scope.$emit('eventName', { message: msg });
};
});
</script>
</head>
<body ng-app="app">
<div ng-controller="firstCtrl" style="border:2px solid #E75D5C; padding:5px;">
<h1>Parent Controller</h1>
<p>Emit Message : </p>
<br />
<div ng-controller="secondCtrl" style="border:2px solid #428bca;padding:5px;">
<h1>Child Controller</h1>
<input ng-model="msg">
<button ng-click="handleClick(msg);">Emit</button>
</div>
</div>
</body>
</html>