简体   繁体   English

如何在AngularJS中的独立组件之间建立通信

[英]How do I establish communication between independent components in AngularJS

I have a Nav in which there are two pages representing two AngularJS components - Home and About . 我有一个净值 ,其中有代表两个AngularJS组件页- HomeAbout I want to pass user name from Home component to About component. 我想将user名从Home组件传递到About组件。

<div ng-app="myApp">
  <ul>
    <li><a href="#!/home">Home</a>
    </li>
    <li><a href="#!/about">About</a>
    </li>
  </ul>
  <div ng-view></div>
</div>

I tried to establish the component communication using bindings with < but no luck. 我尝试使用<但没有运气的bindings来建立组件通信。 Basically, they are both independent components. 基本上,它们都是独立的组件。 How do I pass data from one component to another in this scenario. 在这种情况下,如何将数据从一个组件传递到另一个组件。

I've created a working example using CodePen . 我使用CodePen创建了一个工作示例。 Could anyone please guide how to do it. 任何人都可以指导如何做。

Components and Route Config 组件和路由配置

app.component("home", {
  template: `<h1>Home</h1>
              Hi {{$ctrl.user}}!`,
  controller: function HomeController() {
    this.user = "John.";
  }
});

app.component("about", {
  template: `<h1>About</h1>`,
  controller: function AboutController() {}
});

app.config(function($routeProvider) {
  $routeProvider
    .when("/home", {
      template: "<home></home>"
    })
    .when("/about", {
      template: "<about></about>"
    })
    .otherwise({
      redirectTo: "/home"
    });
});

View data is destroyed when views change. 视图更改时,视图数据将被破坏。 Store data that needs to persist between views in a service: 存储需要在服务的视图之间保留的数据:

app.service("appData", function() {
    var user;
    this.setUser= val => user = val;
    this.getUser= _ => user;
});

Use that service in the component controllers: 在组件控制器中使用该服务:

app.component("home", {
  template: `<h1>Home</h1>
              Hi {{$ctrl.user}}!`,
  controller: function HomeController(appData) {
    this.user = "John.";
    appData.setUser(this.user);
  }
});

app.component("about", {
  template: `<h1>About</h1>`,
  controller: function AboutController(appData) {
      this.user = appData.getUser();
  }
});

For more information, see 有关更多信息,请参见

@georgeawg already answered the question sufficiently. @georgeawg已经充分回答了这个问题。 But I feel one should use sessionStorage when storing username or other userDetails because the date in the service gets erased when the user redirects to other pages. 但是我觉得在存储用户名或其他userDetails时应该使用sessionStorage,因为当用户重定向到其他页面时,服务中的日期会被删除。 Hence storing it once in the sessionStorage can be very helpful. 因此,将其存储在sessionStorage中一次将非常有帮助。

// Create item:
var myObj = { username: 'admin', privilages: 'RAED' };
$window.sessionStorage.setItem(key, JSON.stringify(myObj));

// Read item:
var item = JSON.parse($window.sessionStorage.getItem(key));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM