繁体   English   中英

Angular,当组件不是父/子时,如何将值从一个组件传递到另一个组件?

[英]In Angular, how to pass value from one component to another when the components are not parent/child?

我是 Angular2+ 的新手,阅读了很多资料,包括 Angular 网站。

从 angular 开始,对于父/子我们可以使用 @Input() https://angular.io/guide/template-syntax#input-and-output-properties

但是在我的代码中,我有两个不同的模块,每个模块都有一个组件。

如何将 Module1 的 component1 的 object 值传递给 Module2 的 component2?

我尝试使用 @Input() 但没有成功,并且从上面的 Argular 链接中 @Input() 指的是父/子,这不是我的情况,好吧,据我了解,它不是:)

我可以通过路由、字符串和数字值发送,但不能发送对象,这就是我需要不同方法的原因。

感谢您的任何评论阿德米尔

正如评论中提到的,您可以使用功能齐全的状态管理器,如 Redux。

但是,如果您有一个相当简单的案例,您可以创建一个服务来保存信息,并将该服务注入到两个组件中。

这将要求服务在两个组件都可用的范围内。

App.component.ts

import { Component } from '@angular/core';
import {dataService} from './dataservice.service';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  //name = 'Angular';
  constructor(private SVC: dataService ){

  }
  sender(){
    this.SVC.name="sender"
    console.log("sending this string:    "+this.SVC.name)
  }

}

数据服务.service.ts

import { Injectable } from '@angular/core';

@Injectable()
export class dataService {
name=""
  constructor() { } 
}

已收到.component.ts

import { Component, OnInit } from '@angular/core';
import {dataService} from '../dataservice.service';
@Component({
  selector: 'app-recieved',
  templateUrl: './recieved.component.html',
  styleUrls: ['./recieved.component.css']
})
export class RecievedComponent implements OnInit {
  constructor(private dataservice: dataService ){

  }
  ngOnInit() { 
  }
print(){
  console.log("recieved:    " +this.dataservice.name)
}
}

在这里,我在 app.component 中设置 name = "sender" 并在 received.component.ts 中使用它

演示

您可以简单地使用Angular 服务,阅读 Angular 网站上的“添加服务”教程,多读几遍,您就会完全理解它。
点击这里的网址: https : //angular.io/tutorial/toh-pt4

让我们从创建一个 class(类型)开始;
在此处输入图像描述 对于像我这样一开始很难理解这个概念的人来说,这是一个小例子

现在让我们创建一个服务。

共享数据.service.ts

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
import { SharedData } from './sharedData';

@Injectable()
export class SharedDataService {
  sharedData: SharedData = { prop1: '', prop2: '' };
  private detailSource = new BehaviorSubject<SharedData>(this.sharedData);
  currentDetail = this.detailSource.asObservable();

  constructor() {}

  changeDetail(sharedData: SharedData) {
    this.detailSource.next(sharedData);
  }
}

现在,我们将创建一个组件,您将从中触发消息,(或您想要传递给另一个组件的消息/数据。

太空一号.component.ts

import { Component, OnDestroy, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Subscription } from 'rxjs';
import { SharedDataService } from '../shared/shared-data.service';
import { SharedData } from '../shared/sharedData';

@Component({
  selector: 'app-space-one',
  template: `<p>Component:1, button <br>
  <button (click)="passValue()">pass value</button>
  </p>`,
  styleUrls: ['./space-one.component.css'],
})
export class SpaceOneComponent implements OnInit, OnDestroy {

  constructor(private router: Router, private sharedDataService: SharedDataService) {}

  sharedData: SharedData;
  subscription: Subscription;

  ngOnInit() {
    this.subscription = this.sharedDataService.currentDetail.subscribe(message => this.sharedData =message)

  }

  passValue() {
    let newData = new SharedData();
    newData.prop1 = "new message 1";
    newData.prop2 = "new message 2";
    this.sharedDataService.changeDetail(newData);
    this.router.navigate(['spacetwo'])
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

现在轮到第二个组件接收数据,
空间二.component.ts

import { Component, OnDestroy, OnInit } from '@angular/core';
import { Subscription } from 'rxjs';
import { SharedDataService } from '../shared/shared-data.service';
import { SharedData } from '../shared/sharedData';

@Component({
  selector: 'app-space-two',
  templateUrl: './space-two.component.html',
  styleUrls: ['./space-two.component.css'],
})
export class SpaceTwoComponent implements OnInit, OnDestroy {
  sharedData: SharedData;
  subscription: Subscription;
  //for elucidation only
  prop1: string;
  prop2: string;
  constructor(private sharedDataService: SharedDataService) {}

  ngOnInit() {
    this.subscription = this.sharedDataService.currentDetail.subscribe(
      (data) => (this.sharedData = data)
    );
    //for elucidation
    this.prop1 = this.sharedData.prop1;
    this.prop2 = this.sharedData.prop2;
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

output 与stackblitz中一样,这里实现了一个功能齐全、启用路由的小型应用程序
在此处输入图像描述

暂无
暂无

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

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