How do I pass data to Angular routed components?

前端 未结 16 1109
挽巷
挽巷 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

    say you have

    1. component1.ts
    2. component1.html

    and you want to pass data to component2.ts.

    • in component1.ts is a variable with data say

        //component1.ts
        item={name:"Nelson", bankAccount:"1 million dollars"}
      
        //component1.html
         //the line routerLink="/meter-readings/{{item.meterReadingId}}" has nothing to 
        //do with this , replace that with the url you are navigating to
        
          View
        
      
        //component2.ts
        import { ActivatedRoute} from "@angular/router";
        import 'rxjs/add/operator/filter';
      
        /*class name etc and class boiler plate */
        data:any //will hold our final object that we passed 
        constructor(
        private route: ActivatedRoute,
        ) {}
      
       ngOnInit() {
      
       this.route.queryParams
        .filter(params => params.reading)
        .subscribe(params => {
        console.log(params); // DATA WILL BE A JSON STRING- WE PARSE TO GET BACK OUR 
                             //OBJECT
      
        this.data = JSON.parse(params.item) ;
      
        console.log(this.data,'PASSED DATA'); //Gives {name:"Nelson", bankAccount:"1 
                                              //million dollars"}
         });
        }
      

提交回复
热议问题