在Angular2路由之间传递数据,类似于模态对话框



在Angular2中是否可以从一个路由返回数据到另一个路由?类似于使用模态来搜索/选择一些数据,然后返回。

我在找这样的东西:

  1. 应用开始于/mainRoute
  2. 用户点击搜索按钮
  3. 导航到/search
  4. 加载新的路由/组件
  5. 用户选择X数据
  6. 我"关闭"当前路由(即返回到/mainRoute)
  7. /mainRoute组件现在有X对象

在Angular1中,我做了自己的路由服务,用承诺实现了这一点:

MyRouter.openView('/...../').then(function(returnData){ })

在Angular2中有类似的东西吗?我也读过ngrx/router,但是我没有发现类似的

听起来你想在多个路由组件之间共享数据。一个常见的模式是构建一个服务,该服务被共享/注入到您希望共享该数据的任何组件中。然后,您可以通过服务从每个组件调用写或读数据来获取相同的数据。

顺便说一句,承诺在Angular2中工作得很好。

a.component.ts

import { Component, OnInit } from '@angular/core';
import { SharedService } from './shared.service.ts';
@Component({
  selector: 'my-component-a',
  templateUrl: 'a.component.html'
})
export class ComponentA implements OnInit {
  constructor (private sharedService: SharedService) {}
  ngOnInit () {
    this.sharedService.write('Hello from component A');
  }
}

b.component.ts

import { Component, OnInit } from '@angular/core';
import { SharedService } from './shared.service.ts';
@Component({
  selector: 'my-component-b',
  templateUrl: 'b.component.html'
})
export class ComponentA implements OnInit {
  constructor (private sharedService: SharedService) {}
  ngOnInit () {
    let message = this.sharedService.read();
    // message should now be the string `Hello from component A'
  }
}

shared.service.ts

import { Injectable } from '@angular/core';
@Injectable()
export class SharedService {
  private message: string = null;
  constructor () {}
  read () {
    return this.message;
  }
  write (newMessage: string) {
    this.message = newMessage;
  }
}

ngrx/store也是另一个选项。这里的想法是,你有一个单一的应用程序状态,你在那里存储所有的应用程序数据。你可以调用store来获取数据,也可以调用reducers来更新你的应用数据。光是这个主题就有很多东西要涵盖,所以我强烈建议在尝试这种方法之前先阅读这些内容。

很抱歉写了这么长时间,但我想再补充一点。:)在Angular2中,你可以使用resolve guard预取任何路由的数据。它仍然需要某种服务,你可以从中获取数据。但如果你想让视图准备好进行渲染,这很好。这里有更多关于

的信息

最新更新