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

Ade*_*mir 0 components module send angular

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

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

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

如何将对象值从模块 1 的组件 1 传递到模块 2 的组件 2?

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

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

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

Sha*_*med 5

应用程序组件.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)
  }

}
Run Code Online (Sandbox Code Playgroud)

数据服务.service.ts

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

@Injectable()
export class dataService {
name=""
  constructor() { } 
}
Run Code Online (Sandbox Code Playgroud)

收到的组件.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)
}
}
Run Code Online (Sandbox Code Playgroud)

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

演示