How do I pass data to Angular routed components?

前端 未结 16 1111
挽巷
挽巷 2020-11-22 08:03

In one of my Angular 2 routes\'s templates (FirstComponent) I have a button

first.component.html

16条回答
  •  太阳男子
    2020-11-22 08:31

    Angular 7.2.0 introduced new way of passing the data when navigating between routed components:

    @Component({
      template: `Go`,
    })
    export class AppComponent  {
      constructor(public router: Router) {}
      navigateWithState() {
        this.router.navigateByUrl('/123', { state: { hello: 'world' } });
      }
    }
    

    Or:

    @Component({
      selector: 'my-app',
      template: `
      Go`,
    })
    export class AppComponent  {}
    

    To read the state, you can access window.history.state property after the navigation has finished:

    export class PageComponent implements OnInit {
      state$: Observable;
    
      constructor(public activatedRoute: ActivatedRoute) {}
    
      ngOnInit() {
        this.state$ = this.activatedRoute.paramMap
          .pipe(map(() => window.history.state))
      }
    }
    
        

    提交回复
    热议问题