Angualr2如何将数据从一个控制器发送到其他wthout url参数,如$ state.go()

时间:2017-12-11 11:03:30

标签: angular typescript angular2-routing

我正在尝试将参数从一个控制器传递到另一个控制器,但我不想传入url(需要隐藏)我试图传递

this.router.navigate(['/collections/'+this.name], {id: this.id});

但在其他控制器上我无法访问它我也试过

    {
      path: 'collection/:city',
      component: Component,
      data : {id : null}
    }

但是在这里我如何传递id动态,因为在路由文件中我没有id值可以从组件传递。

在angulajs1.5中,我们使用params hash来隐藏来自url的id。

$state.go('collection', {id: 10})

 state('collection', {
    url : '/collection',
    params : {
        id : null,
    },
    templateUrl : templatesDir + 'collection.html',
    controller : 'collectionController',
})

在angularjs2中有没有相同的方法

由于

2 个答案:

答案 0 :(得分:1)

您需要创建单个对象,以在多个组件之间共享它。

  1. 用作服务。 Angular2中的@injector。 @injector
  2. 在一个类中创建static members,然后使用类名在其他类中访问它们。
  3. 这两种方式。

答案 1 :(得分:0)

为了在控制器之间共享数据,您可以将其存储在工厂/服务中。工厂可以保存您的数据,因为它是单个对象(仅在刷新之前)。

存储在工厂中的最佳做法是使用getter / setter对象。

通过此链接了解其他方法

https://angularfirebase.com/lessons/sharing-data-between-angular-components-four-methods/