Passing data through Angular2 router

后端 未结 7 742
暖寄归人
暖寄归人 2020-12-24 14:01

I have a component where I select a set of image objects. I want to pass these selected images to my new route, CreateAlbum. The data it nested and wouldn\'t be suitable to

相关标签:
7条回答
  • 2020-12-24 14:37

    Angular >= 7.2.0 introduced a new way of passing the data when navigating between routed components. In NavigationExtras interface within the router module was added a new attribute: state: any and you can set the data which will be present in the new state.

    In component

    export class ComponentA {
        constructor(private router: Router) {}
    
        goToComponentB(): void {
            // programmatically        
            this.router.navigate(['/b'], {state: {data: {...}}});
        }
    }
    

    In HTML

    <a routerLink="/b" [state]="{ data: {...}}">Go to B</a>
    
    

    Get data in Component B using history.state.data

    export class ComponentB {
        constructor() {
           console.log(history.state.data); // GET DATA
        }
    }
    

    Thanks to Ľudovít Hajzer Read the whole blog here https://medium.com/ableneo/how-to-pass-data-between-routed-components-in-angular-2306308d8255

    0 讨论(0)
提交回复
热议问题