[英]Angular 2 pass data between two components
我想在兩個組件之間傳遞數據,但我的問題是:
我有兩個組件,假設一個是“主要”,另一個是“模態對話框”。
在我的主要內容中,我想打開模態對話框並從我的模態對話框中獲取數據而不離開我的主要組件
我知道如何使用 @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 發送一條消息,例如,如果我關閉它或單擊某個按鈕。
看看@Output
<modal-dialog [data]="data" (DialogEvent)="processEvent($event)"> </modal-dialog>
在 ModalDialogComponent 中
@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"}
}
我建議最好的方法是使用 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);
})
}
通過這種方式,您可以輕松地在任何組件之間傳遞數據。
有關組件之間的各種通信,請參閱此鏈接。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.