Angular 2在路由时传递对象

标签 angular oop typescript routes

我试图在路由时在页面之间传递一个对象(数组)。为此,我做了this answer说了,但这对我不起作用。

服务

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

父级

import { ReportService } from './';

@Component({
  providers: [ReportService]
})

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

子级 1

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

export class ReportHomeComponent {

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

子 2

import { ReportService } from '../';

@Component({
})

export class ReportStatsComponent {

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

如果我点击第一个 child 中的a,我会被重定向到第二个 child 。在更改页面之前,selectedReports[] 已填充。换页后就空了。我错过了什么吗?

我知道之前已经有人问过这个问题,但我决定还是根据问题顶部链接中给出的答案的评论部分中的要求提出这个问题。

最佳答案

您可能会以两种不同的方式导入服务。在您正在使用的父组件中:

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

这会创建一个新实例并将其注入(inject)到该组件和子组件树中。

如果您在 @NgModuleproviders 数组中也指定了 ReportService,那么子级可能会从那里获取其实例。

对于这样的共享服务,我建议仅将服务添加到 @NgModule 中的 providers 数组中。这为该模块中的所有组件提供了一个实例。而组件装饰器中的 providers 数组为该组件提供了一个唯一的实例。

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

关于Angular 2在路由时传递对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43001080/

相关文章:

javascript - JQuery 不附加带有 JS 函数对象属性的 div 标签

TypeScript:从枚举类型推断枚举值类型

javascript - 如何捕获http状态

Angular 为 :host in ngOnInit 设置 css 样式

forms - Angular2 可编辑表单以及使用 Observables 的服务

image - Angular 2 : Dynamic Images

java - 为什么构造函数的名称不能与类名不同,只要它们是唯一的

PHP/MySQL : Database class and dependency injection

angular - 与可观察对象并行读取文件

angular - 动态更新的 ng2-charts