Angular 2 passing objects when routing

2019-07-11 17:36发布

问题:

I am trying to pass a object (array) between pages when routing. For this I did exactly what this answer said but it doesn't work for me.

Service

@Injectable ()
export class ReportService extends HttpService {

    public selectedReports: any[] = [];

    public setSelectedReports (id: string, value: any) {
        this.selectedReports[id] = value;
    }

    public removeSelectedReports (id: string) {
         delete this.selectedReports[id];
    }
}

Parent

import { ReportService } from './';

@Component({
  providers: [ReportService]
})

export class ReportComponent {
  constructor (private reportService: ReportService) {}
}

Child 1

import { ReportService } from '../';
@Component({
  template: '<a [routerLink]="['stats']">Stats</a>'
})

export class ReportHomeComponent {

  constructor (private reportService: ReportService) {
    reportService.setSelectedReports (1, 'hello')
  }
}

Child 2

import { ReportService } from '../';

@Component({
})

export class ReportStatsComponent {

  constructor (private reportService: ReportService) {
    console.log(reportService.selectedReports)
  }
}

If I click on the a in the first child I get redirected towards the second child. Before changing pages, the selectedReports[] is filled. After changing pages, it is empty. Am I missing something?

I know this question has been asked before but I decided to ask the question anyway on request within the comment section of the answer given in the link at the top of the question.

回答1:

You might be importing the service two different ways. In the parent component you are using:

@Component({
  providers: [ReportService]  //<--unique instance injected into this component
})

This creates a new instance and injects it into this component and sub-component tree.

If you have the ReportService also specified in the providers array of your @NgModule then the children are likely getting their instance from there.

For shared services like this, I recommend only adding the service to the providers array in the @NgModule. This provides a single instance to all components in that module. Whereas the providers array in the component decorators provides a unique instance to that component.

@NgModule({
  imports: [
    ...
  ],
  declarations: [
    ...
  ],
  providers: [ReportService],  //<--inject service here to be global to module
  bootstrap: [AppComponent]
})