2017-06-27 72 views
0

我不知道如何讓它變好。 我想在兩個角度組件之間發送JSON。我在考慮路由,但是如何在POST之間發送類似於POST的內容,我知道如何使用@ inputs/@ Outputs,但我必須更改URL並重新加載內容。問題是它不僅是id,而且還包括檢查標識列表。如何通過路由發送2個組件Angular 2之間的Array/list/JSON?

組件

selectedAll = [];// it is array od Id [1,2,3,4...]; 
    goToDetail(): void { 
    this.selectedIDService.saveIds(this.selectedLight); 
    console.log("Show: "+this.selectedIDService.retrieveIDs().length); <-- give me good number 

    this.router.navigate(['/detailSearch']); 
    } 

HTML按鈕nothong intresting

<button class="btn btn-success dropdown-toggle" type="button" data-toggle="dropdown" (click)="gotoDetail()"> 

我當然希望得到這個在我的detailSearch組件。

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

@Injectable() 
export class SelectedIdService { 

    public myIds: Array<Number>=[]; 
    constructor() { } 

    saveIds(produIds:any){ 
    this.myIds = produIds; 
    console.log(this.myIds); 
    } 
    retrieveIDs():any[]{ 
    return this.myIds; 
    } 
} 

--------其他成分-------

providers : [SelectedIdService] 
constructor(private route: ActivatedRoute, 
       private selectedIdService :SelectedIdService) { } 
    ngOnInit() { 
    var selected:any[] =this.selectedIdService.retrieveIDs();<<-- empty 
} 

做你知道爲什麼嗎?

回答

2

使用service將ID數組從一個組件保存到其他組件。將它傳遞給url並不是一種安全的方式。

創建這樣的服務,

import { Injectable } from '@angular/core'; 
@Injectable() 
export class AppMessageQueuService { 

    myIds: Array<Number>=[]; 
    constructor() { 

    } 
    saveIds(produIds:any){ 
     this.myIds = produIds; 
    } 
    retrieveIDs(){ 
     return this.myIds; 
    } 

} 

然後你可以注入本服務到兩個組件,它從第一部件一樣保存,

this.appMsgService.saveIds(yourIds); 

然後檢索第二組件作爲,

this.appMsgService.retrieveIDs(yourIds); 

你可以注入你的組件,

constructor(
    private appMsgService: AppMessageQueuService 
) 
+0

也許它是不安全的,但它是工作業務要改變鏈接,所以我必須這樣做。 – Mistu

+0

在其他組件中我有空陣列:( – Mistu

+0

這不是問題:) – Sajeetharan

1

在2個Angular Components之間發送JSON,您需要使用提供者服務。 official docs

相關問題