How do I pass data to Angular routed components?

前端 未结 16 1373
挽巷
挽巷 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:44

    I this the other approach not good for this issue. I thing the best approach is Query-Parameter by Router angular that have 2 way:

    Passing query parameter directly

    With this code you can navigate to url by params in your html code:

    
    

    Passing query parameter by Router

    You have to inject the router within your constructor like:

    constructor(private router:Router){
    
    }
    

    Now use of that like:

    goToPage(pageNum) {
        this.router.navigate(['/product-list'], { queryParams: { serviceId: serviceId} });
    }
    

    Now if you want to read from Router in another Component you have to use of ActivatedRoute like:

    constructor(private activateRouter:ActivatedRouter){
    
    }
    

    and subscribe that:

      ngOnInit() {
        this.sub = this.route
          .queryParams
          .subscribe(params => {
            // Defaults to 0 if no query param provided.
            this.page = +params['serviceId'] || 0;
          });
      }
    

提交回复
热议问题