2017-07-05 94 views
1

我有一個項目使用角2和UI-ROUTER(不是NgRoute)。角2 ui路由器:更改父狀態中的數據

它具有:
父狀態「父」,控制部首控制的視圖,如圖所示在下面的圖片,
兩個子狀態「childA」和「childB」,控制所述圖孩子enter image description here

在進入任何一個子狀態的說「childAState」的,我需要通過一些文字,如「childA」,到母公司國有控股視圖。我該怎麼做?進入孩子狀態時如何將數據傳遞給父母狀態?

此'childA'文本與任何組件無關,但與其進入的子狀態有關。 (所以我不認爲我應該讓它通過組件樹。)

我所定義的狀態是這樣的:

export const parentState = { 
    name: 'parent', 
    url: '', 
    redirectTo: 'childA', 
    views: { 
     'header': { 
      component: HeaderComponent 
     }, 
     'control-panel': { 
      component: ControlComponent 
     } 
    } 
}; 
export const childAState = { 
    name: 'childA', 
    parent: 'parent', 
    url: '/childA', 
    views: { 
     '[email protected]': { 
      component: LayerAComponent 
     } 
    } 
}; 
export const childBState = { 
    name: 'childB', 
    parent: 'parent', 
    url: '/childB', 
    views: { 
     '[email protected]': { 
      component: LayerBComponent 
     } 
    } 
}; 

謝謝!

回答

1

您需要有服務BehaviorSubject。父母將觀察該服務數據。

當子組件想要通知父代時,它會更新服務。由於父母正在觀察服務數據,因此會收到通知並執行操作。這是組件以角度進行通信的方式之一,您可以使用該方法。

+0

如果我使用BehaviorSubject,我應該在哪裏觸發呢?因爲我需要在進入子狀態時傳遞數據,我應該使用像onEnter這樣的子狀態並執行dataBehaviorSubject.next('someData')? – Viv

+0

就是這樣的 – Skeptor

1

你的狀態data財產將數據,像這樣的例子:

export const childAState = { 
    name: 'childA', 
    parent: 'parent', 
    url: '/childA', 
    data: { 
     childData: 'childA' 
    }, 
    views: { 
     '[email protected]': { 
      component: LayerAComponent 
     } 
    } 
}; 

在你HeaderComponent你可以聽狀態的變化,無論是使用過渡掛鉤或router.globals.success$觀測。

import { TransitionService } from '@uirouter/angular'; 

@Component({}) 
class HeaderComponent { 
    private unsub: Function; 
    constructor(public transService: TransitionService) {} 

    ngOnInit() { 
    this.unsub = this.transService.onSuccess({}, transition => { 
     const to = transition.to(); // The state that was just activated 
     if (to.data && to.data.childData) { 
     // do something 
     } 
    }); 
    } 

    ngOnDestroy() { 
    this.unsub(); 
    } 
} 

import { UIRouter } from '@uirouter/angular'; 

@Component({}) 
class HeaderComponent { 
    private sub: Subscription; 
    constructor(public router: UIRouter) {} 

    ngOnInit() { 
    this.sub = router.globals.success$.subscribe({}, transition => { 
     const to = transition.to(); // The state that was just activated 
     if (to.data && to.data.childData) { 
     // do something 
     } 
    }); 
    } 

    ngOnDestroy() { 
    this.sub.unsubscribe(); 
    } 
} 
相關問題