我试图在路由时在页面之间传递对象(数组)。为此我做了什么这个答案 https://stackoverflow.com/questions/35478994/angular-2-passing-object-via-route-params-possible说但这对我不起作用。
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)
}
}
如果我点击a
在第一个孩子中,我被重定向到第二个孩子。在更改页面之前,selectedReports[]
充满。换页后就空了。我错过了什么吗?
我知道这个问题之前已经被问过,但我决定无论如何根据问题顶部链接中给出的答案的评论部分中的要求提出这个问题。
您可能会以两种不同的方式导入服务。在您正在使用的父组件中:
@Component({
providers: [ReportService] //<--unique instance injected into this component
})
这将创建一个新实例并将其注入到该组件和子组件树中。
如果您有ReportService
中还指定了providers
你的数组@NgModule
那么孩子们很可能会从那里得到他们的实例。
对于这样的共享服务,我建议仅将服务添加到providers
数组中的@NgModule
。这为该模块中的所有组件提供了一个实例。鉴于providers
组件装饰器中的数组为该组件提供了唯一的实例。
@NgModule({
imports: [
...
],
declarations: [
...
],
providers: [ReportService], //<--inject service here to be global to module
bootstrap: [AppComponent]
})
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)