【问题标题】:In Angular, how to pass value from one component to another when the components are not parent/child?在 Angular 中,当组件不是父/子时,如何将值从一个组件传递到另一个组件?
【发布时间】:2020-05-22 21:59:26
【问题描述】:

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

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

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

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

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

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

感谢任何cmets 阿德米尔

【问题讨论】:

  • 你可能:需要重构你的 Angular 模块以保持清晰的组件树或者使用像 Redux 这样的状态管理器
  • 谢谢 Guido,我创建了模块以避免所有组件都位于 SRC 文件夹下。无论如何,我会看看如何更好地解决这个问题。

标签: angular module components send


【解决方案1】:

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

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

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

【讨论】:

  • 非常感谢 Grey,它成功了!!!我阅读了有关服务、getter 和 setter 的信息,它在两个组件中注入服务效果很好
【解决方案2】:

您可以简单地使用Angular服务,阅读Angular网站上的'添加服务'教程,多读几遍,你就会完全明白。 点击网址:https://angular.io/tutorial/toh-pt4

【讨论】:

    【解决方案3】:

    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 中设置 name = "sender" 并在 received.component.ts 中使用它

    demo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-05-02
      • 2020-05-08
      • 1970-01-01
      • 2020-12-30
      • 1970-01-01
      • 2021-10-31
      相关资源
      最近更新 更多