0

I have no idea how to make it good. I want to send JSON between 2 Angular Components. I thinking about routing but how to send something like POST between this, to components i know how to use @inputs/@Outputs , but i have to change Url and reload content. The problem is it is not only id but list of check ides.

Component

  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 button nothong intresting

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

Of course i want to get this on my detailSearch component.

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;
  } 
}

--------Other component-------

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

do u know why?

2 Answers 2

2

Use a service to save the array of ids from one component to other component. It's not a safe way to pass it over the url.

Create a service like this,

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

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

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

}

Then you can inject this Service into both the components and save it from the first component like,

this.appMsgService.saveIds(yourIds);

then retrieve in the second component as,

this.appMsgService.retrieveIDs(yourIds);

you can inject to your component as,

constructor(
   private appMsgService: AppMessageQueuService
)
Sign up to request clarification or add additional context in comments.

4 Comments

maybe it is not safe, but it is working business want to change link so i have to make it like this.
in the Other components i have empty array :(
That is not an issue :)
selected-id.service.ts:11 (4) [1, 2, 3, 4] search-standard.component.ts:87 show: 4 detail-result.component.ts:29 show 0
1

Send JSON between 2 Angular Components, you need to use a provider service. official docs

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.