2017-07-05 93 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(); 
    } 
} 
相关问题