2017-08-16 65 views
1

想,我有一個componentA和以componentB如何在angular2中將數據從一個子組件傳遞到另一個子組件?

@Component({ 
    selector: 'appA', 
    templateUrl: './appA.html', 
    styleUrls: ['./appA.css'] 
}) 
export class componentA{ 
    constructor(private route: Router) { } 
    moveFront() { 
    this.route.navigateByUrl('componentB'); 
    } 
} 

@Component({ 
    selector: 'appB', 
    templateUrl: './appB.html', 
    styleUrls: ['./appB.css'] 
}) 
export class componentB{ 
    constructor(private route: Router) { } 
    moveBack() { 
    this.route.navigateByUrl('componentA'); 
    } 
} 

現在,當我打電話moveFront()函數,以componentB被調用,但我想通過一些數據,以及到組件,我該怎麼辦呢?

我的組件都是一個子組件,我想將數據從一個子組件傳遞到另一個子組件。我該怎麼做。

+0

我會使用商店來做到這一點,並在我導航到新組件之前分配我希望在商店和商店之間共享的任何內容,而當其他組件啓動時,我會訂閱該商店並獲取價值。你也可以使用服務並在服務中設置一個變量,當創建第二個組件時,它可以主動從服務中獲取該變量。 – Kevin

+0

[Angular2在兩個子組件之間傳遞數據]的可能副本(https://stackoverflow.com/questions/38254379/angular2-passing-data-between-two-child-components) –

+0

使用'ngrx'或服務 –

回答

2

另一個選項(如果您只發送字符串值)是使用Route參數。與查詢參數類似,它可能有一些相當粗糙的URL,但它是一個選項。首先,你要注入ActivatedRoute

constructor(private router: Router, private route:ActivatedRoute) { } 

你會使用router.navigate代替:

this.router.navigate(['componentB', {myVar:'myValue'}]); 

然後在你的組件,訂閱路線PARAMS:

ngOnInit() { 
    this.route.params.subscribe((data) => { 
    this.myVar = data.myVar || 'defaultValue'; 
    }); 
} 

同樣,這隻適用於字符串。對使用此方法傳遞的任何對象的角度調用.toString()。如果你想發送更復雜的數據,你應該使用服務/商店。

+0

使用JSON字符串,並且您有大量可用的數據 –

相關問題