2016-09-24 113 views
0

是否可以在Angular2中將數據從一條路徑返回到另一條路徑?類似於使用模態來搜索/選擇一些數據,然後將其返回。在類似於模式對話框的Angular2路由之間傳遞數據

我正在尋找這樣的事情:

  1. 的應用始於/ mainRoute
  2. 的用戶在點擊搜索按鈕
  3. 導航到/搜索
  4. 加載新的路線/組件
  5. 用戶選擇X數據
  6. 我「關閉」當前路線(即返回到/ mainRoute)
  7. /mainRoute組件現在已經在X對象

在Angular1我這樣做,有承諾實現這個我自己的路由服務:

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

有沒有這樣的事情在Angular2?我也讀了ngrx/router,但我沒有發現類似的東西。

回答

0

這聽起來像你想在多個路由組件之間共享數據。一種常見的模式是構建一個服務,該服務共享/注入您想共享該數據的任何組件。然後,您可以通過每個組件的服務調用寫入或讀取數據來獲取相同的數據。

BTW承諾在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也是另一種選擇。這裏的想法是,您有一個應用程序狀態,您可以在其中存儲所有應用程序數據。您可以打電話到商店取數據,或者您可以撥打減少人數這將更新您的應用程序數據。單是這個話題就很多,所以我強烈建議在嘗試這種方法之前先閱讀一下。

對不起長時間的寫作,但又想補充一點。 :) 在Angular2中,有一個resolve guard可用於預取任何路由的數據。它仍然需要某種可以從中獲取數據的服務。但是如果你希望你的視圖能夠在你看到的時候做好渲染的準備,那麼這很好。 Here's more info about that