【问题标题】:Update parent component when navigating from child Component (Angular)从子组件(Angular)导航时更新父组件
【发布时间】:2017-05-03 00:54:01
【问题描述】:

从子组件路由时,我在更新父组件时遇到了一些问题。我通过研究发现了这么多,是 ngOnInit 只被调用一次,但是如何解决这个问题?我尝试了不同的生命周期钩子,但要么我无法正确使用它们,要么我根本不应该使用它们!有人可以帮忙吗?谢谢!

我的路线:

{
    path: 'dashboard',
    component: DashboardComponent,
    children: [
        {
            // when user is on dashboard component, no child component shown
            path: '', 
        },

        {   // detail component
            path: ':table/:id', // 
            component: DetailComponent,
        },
        //some more child routes and components...
    ]
}

仪表板组件中的ngOnInit(父)

ngOnInit() {
    this.getSomething1(); // this populates an array
    this.getSomething2(); // this populates an array
}

当用户从上述数组之一中选择一个项目时,用户会被路由到该项目的详细信息页面 (DetailComponent),用户可以在其中更新/删除该项目。

子组件中的方法,当用户删除项目时,用户被路由到父组件:

deleteItem(item: any) {
    // some code... 
    this._router.navigate(['dashboard']); 
}

所以一切正常,除了项目数组没有更新,因为 ngOnInit 只被调用一次。

所以当用户从子组件DetailComponent 被路由回DashboardComponent 时,我想运行getSomething1()getSomething2() 方法。

感谢您的帮助!

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    解决这种情况的方法是使用主题。

    在 DashboardComponent 中你可以声明一个主题:

    public static returned: Subject<any> = new Subject();
    

    并订阅它:

    constructor() {
          DashboardComponent.returned.subscribe(res => {
             this.getSomething1(); // this populates an array
             this.getSomething2();
          });
       }
    

    在DetailComponent中,删除item后,在subject中调用next:

    deleteItem(item: any) {
        // some code... 
        DashboardComponent.returned.next(false);
        this._router.navigate(['dashboard']); 
    }
    

    【讨论】:

    • 谢谢,这就像一个魅力!只需将DetailComponent.returned.next(false) 更改为DashboardComponent.returned.next(false),我会接受答案! :) 非常感谢!
    • 不用担心@ASomeOneJ!刚刚改错了。
    猜你喜欢
    • 2020-01-31
    • 2018-07-15
    • 2021-02-10
    • 2021-08-30
    • 1970-01-01
    • 2023-02-20
    • 2021-02-27
    • 2020-11-10
    • 2017-11-23
    相关资源
    最近更新 更多