简体   繁体   English

在组件之间共享 angular 中的数据

[英]Sharing data in angular between components

I am new to angular and working on a application.我是 angular 的新手,正在开发一个应用程序。 I have a "Save" button in my page.我的页面中有一个“保存”按钮。 On click of which I need to route to a page.点击我需要路由到一个页面。 With click of this save button, I also want to send a array to next routed component.单击此保存按钮后,我还想将数组发送到下一个路由组件。 I want to recieve that array in next component.我想在下一个组件中接收该数组。 Both the component are at same level两个组件处于同一级别

As per many tutorial sending in query params is not a good idea.根据许多教程发送查询参数不是一个好主意。 I was thinking to make a getter and setter in a service and calling getter method in routed component and access the array.我正在考虑在服务中创建一个 getter 和 setter,并在路由组件中调用 getter 方法并访问数组。 But not sure whether it is a good approach or not.但不确定这是否是一个好方法。 Then how I can send my data to next page?那么我如何将我的数据发送到下一页?

You can either use the approach @Suhas suggested or handle your state via BehaviourSubjects and Observabels.您可以使用@Suhas 建议的方法,也可以通过 BehaviourSubjects 和 Observabels 处理您的 state。 So first you create a service in which you define your behaviourSubject and the according Observable:因此,首先您创建一个服务,在其中定义您的 behaviorSubject 和相应的 Observable:

private currentRouteSubject$ = new BehaviorSubject('initalValue');
currentRouteObservable = currentRouteSubject$.asObservable();

Then, in that service, you define a method which gets called whenever the user navigates or clicks that button:然后,在该服务中,您定义一个在用户导航或单击该按钮时调用的方法:

setNavigationData(someData) {
this.currentRouteSubject$.next(someData);
}

Now in your other component, you subscribe to that Observable and you will get the latest emitted value.现在在您的其他组件中,您订阅了该 Observable,您将获得最新发出的值。 So that means you only need to inject the Service via Dependency Injection in your two components.所以这意味着你只需要在你的两个组件中通过依赖注入注入服务。 In the first you need the service so you can call the setNavigationData function, In the second component you need the service because you have to subscribe to the Observable which, at the end, holds the latest emitted value.在第一个组件中,您需要该服务,因此您可以调用 setNavigationData function,在第二个组件中,您需要该服务,因为您必须订阅 Observable,该 Observable 最后保存最新发出的值。 Thats the approach I use.这就是我使用的方法。

You can either你可以

  1. Use a store like NgRx使用像 NgRx 这样的商店
  2. Simply create your own store in a file like store.ts = const store = {data1: {}}; export default store;只需在 store.ts = const store = {data1: {}}; export default store;这样的文件中创建您自己的商店const store = {data1: {}}; export default store; Then import the store in component1 and assign data to data1.然后在component1中导入store,给data1赋值。 The data change will reflect to any component that imported it.数据更改将反映到导入它的任何组件。 But be careful not to modify store itself.但注意不要修改 store 本身。 It will lose any reference.它将失去任何参考。
  3. Use service class members to store data.使用服务 class 成员来存储数据。 You can inject the service to any component that needed to modify or retrieve the data.您可以将服务注入任何需要修改或检索数据的组件。

You can make use of navigationExtras to send an object via router.您可以使用navigationExtras通过路由器发送 object。 You don't need any third party library, just inject the router in the constructor and make use of it您不需要任何第三方库,只需在构造函数中注入路由器并使用它

import { NavigationExtras, Router } from "@angular/router";    
constructor(private _router: Router) {}    
    const navigationExtras: NavigationExtras = {
              state: {
                studentList: this.students
              },
            };

While navigating you can send the navigation extras like below导航时,您可以发送导航附加信息,如下所示

this._router.navigate([], navigationExtras).then((result) => {
      // We have to hard code base href whenver we use window.open
      window.open(redirectionUrl, "_blank");
    });

Here is the demo link这是演示链接

Use package https://www.npmjs.com/package/ngx-navigation-with-data使用 package https://www.npmjs.com/package/ngx-navigation-with-data

First you need to import the NgxNavigationWithDataComponent class in you app.module.ts Define some path in app-routing.module.ts file Import the NgxNavigationWithDataComponent class in your componet where you want to use this package Now you can use the package's methods. First you need to import the NgxNavigationWithDataComponent class in you app.module.ts Define some path in app-routing.module.ts file Import the NgxNavigationWithDataComponent class in your componet where you want to use this package Now you can use the package's methods. app.module.ts app.module.ts

import { NgxNavigationWithDataComponent } from "ngx-navigation-with-data";
@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    AppRoutingModule
  ],
  providers: [NgxNavigationWithDataComponent],
  bootstrap: [AppComponent]
})
export class AppModule { }

app-routing.module.ts应用程序路由.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';

const routes: Routes = [
  {
    path:'home',
    component:HomeComponent
  },
    {
    path:'about',
    component:AboutComponent
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

home.component.ts home.component.ts

import { Component, OnInit } from '@angular/core';
import { NgxNavigationWithDataComponent } from 'ngx-navigation-with-data';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  constructor(public navCtrl: NgxNavigationWithDataComponent) { }

  ngOnInit() {
  }

  navigateToABout() {
  this.navCtrl.navigate('about', {name:"virendta"});
  }
  
}

about.component.ts about.component.ts

import { Component, OnInit } from '@angular/core';
import { NgxNavigationWithDataComponent } from 'ngx-navigation-with-data';

@Component({
  selector: 'app-about',
  templateUrl: './about.component.html',
  styleUrls: ['./about.component.css']
})
export class AboutComponent implements OnInit {

  constructor(public navCtrl: NgxNavigationWithDataComponent) {
    console.log(this.navCtrl.get('name')); // it will console Virendra
    console.log(this.navCtrl.data); // it will console whole data object here
  }

  ngOnInit() {
  }

}

Properties特性

get(key): method It will return the value of data object from previous component get(key): 方法 它将返回前一个组件的数据 object 的值

data: get property It will give the whole data object of previous component data: get property 它将给出前一个组件的整个数据 object

navigate(page, data): method It will navigate to the component name of page, in routing.module file, with data导航(页面,数据):方法它将导航到页面的组件名称,在routing.module文件中,带有数据

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

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