【问题标题】:Angular 2 pass data between two componentsAngular 2 在两个组件之间传递数据
【发布时间】:2018-02-22 20:01:41
【问题描述】:

我想在两个组件之间传递数据,但我的问题是:

我有两个组件,假设一个是“main”,另一个是“modal-dialog”。

在我的主要部分中,我想打开模态对话框并从我的模态对话框中获取数据,而无需离开我的主要组件

我知道如何使用@Input,但在我的应用程序中看不到使用它的方法

例如在我的 main.html 中,如果我想将数据从 main 传递到 modal 我会使用

<modal-dialog [data]="data"> </modal-dialog>

但我想反其道而行之

类似的东西

<modal-dialog /*get data from modal when event happens*/ > </modal-dialog> 

Modal-dialog 会为我的 main 发送一条消息,例如,如果我关闭它或单击某个按钮。

【问题讨论】:

标签: angular


【解决方案1】:

查看@Output

<modal-dialog [data]="data" (DialogEvent)="processEvent($event)"> </modal-dialog>

在模态对话框组件中

@Output()
public DialogEvent = new EventEmitter();

public methodWhichTriggers(){
   this.DialogEvent.emit({id: 1, type: "anything you need"})
}

在 MainComponent 中你需要有

public processEvent($event){
   console.log($event); //will print {id: 1, type: "anything you need"}
}

【讨论】:

  • 我会试试的。非常感谢!
【解决方案2】:

我建议最好的方法是使用 rxjs 主题。您可以在模态对话框组件或其他任何组件之间传递数据。像这样在您的服务中创建新的 rxjs 主题

import { Subject } from 'rxjs/Subject';
@Injectable()
export class MyService {

    myNewSubject = new Subject<any>();

    informDataChanges(passyourobject){
      this.myNewSubject.next(passyourobject);
  }

}

当您的组件发生更改或您想将数据传递给另一个组件时,只需从您的组件调用此服务函数并将数据作为参数传递给此函数。你可以用这样的东西来做到这一点

    import { Component, OnInit } from '@angular/core';

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

      constructor( private myService: MyService) { }

      someFunction(){
        this.myService.informLogout('somedata');//Passing data to service here
      }

  ngOnInit() {

  }

}

现在您需要做的就是在另一个组件中订阅该数据。重要的主题会持续关注它的任何变化,并且数据将是连续的流并且它会被自动订阅。所以最好在构造函数中订阅主题,更改会立即反映在该组件中。

你用这样的东西来做

import { Component, OnInit } from '@angular/core';

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

          constructor( private myService: MyService) {
            this.myService.myNewSubject.subscribe(data=>{
             console.log(data);
       }) 
}

通过这种方式,您可以轻松地在任何组件之间传递数据。

【讨论】:

    【解决方案3】:

    组件之间的各种通信请参考this链接。

    【讨论】:

      猜你喜欢
      • 2017-08-12
      • 2017-01-12
      • 2020-10-10
      • 1970-01-01
      • 2016-04-29
      • 1970-01-01
      • 2017-09-21
      • 2016-07-20
      相关资源
      最近更新 更多