路由时有角度的2个传递对象 [英] Angular 2 passing objects when routing

查看:80
本文介绍了路由时有角度的2个传递对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在路由时在页面之间传递对象(数组)。为此,我确实做了此答案所说的,但它没有

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.

服务

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

如果单击在第一个孩子的 a 上,我被重定向到第二个孩子。在更改页面之前,已填写 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.

推荐答案

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

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.

如果您还具有提供者 ReportService >您的 @NgModule 的数组,则孩子很可能从那里获取实例。

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

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

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

这篇关于路由时有角度的2个传递对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆