在 Angular 中,当组件不是 parent/child 时,如何将值从一个组件传递到另一个组件?

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

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

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

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

如何将对象值从 Module1 的 component1 传递给 Module2 的 component2?

我试过 @Input() 但没有成功,从上面的 Argular link @Input() 指的是 parent/child 这不是我的情况,好吧,根据我的理解这不是:)

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

感谢任何意见 阿德米尔

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

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

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

您可以简单地使用 Angular 服务,阅读 'Add services' 教程 Angular网站,多看几遍,你就完全明白了。
单击此处 url:https://angular.io/tutorial/toh-pt4

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)
  }

}

dataservice.service.ts

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

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

recieved.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中设置名称="sender"并在received.component.ts

中使用它

demo

让我们开始创建一个class(类型);
对于像我这样一开始很难理解概念的人来说,这是一个小例子

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

shared-data.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);
  }
}

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

space-one.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();
  }
}

现在轮到第二个组件接收数据,
space-two.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();
  }
}

输出如 stackblitz, a small fully functional, with routing enabled has been implemented here