Angular 2 passing objects when routing

你说的曾经没有我的故事 提交于 2019-12-11 02:29:54

问题


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]
})


来源:https://stackoverflow.com/questions/43001080/angular-2-passing-objects-when-routing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!