在Angular 2中使用传递变量进行路由?

Posted

技术标签:

【中文标题】在Angular 2中使用传递变量进行路由?【英文标题】:Routing with passing variable in Angular 2? 【发布时间】:2020-07-20 16:02:29 【问题描述】:

我有两个组件。首先,我得到一个输入值,我想路由到传递输入值的第二个组件。在第二个组件中,我想打印这个输入值。

first.component.html

<div class="center">

<h1 id="title" class="title">Είσοδος</h1>

&nbsp;
    &nbsp;
    &nbsp;
 &nbsp;
</div>
<div class="center">
<p class="sub-title">Εισάγετε το token σας </p>
</div>
<div class="center">


    &nbsp;
    &nbsp;
    &nbsp;


    &nbsp;



          <label  class="label" for="input-password">Token:  </label>

        <input nbInput
        fullWidth type="text" (ngModel)="token" #passa>



    </div>
  <div class = "center">


    <pre>

    </pre>
    <pre></pre> 

    <button class="button1"  (click)="pass(passa)"> 
      Είσοδος
    </button> 



  </div>

first.component.ts

    import Component, OnDestroy,OnInit, Input from '@angular/core';
import  ChangeDetectorRef  from '@angular/core';
import  Router  from '@angular/router';
import  analyzeAndValidateNgModules  from '@angular/compiler';
import  ParkingService  from '../../../services/parking.service';
import  Injectable  from '@angular/core';
import  Subject, BehaviorSubject  from 'rxjs';



@Component(
    selector: 'ngx-homepage',
    styleUrls: ['./homepage.component.scss'],
    templateUrl: './homepage.component.html',
    providers: [ParkingService]

  )

  @Injectable()
  export class HomepageComponent implements OnInit 


    a:string;
  constructor (public parkingService: ParkingService, public root:Router)  


  
  ngOnInit()


  

        pass(passa)
          

          this.a= passa.value;
          window.alert(this.a);
          this.parkingService.setUserToken(this.a);

          this.root.navigate(['/pages/iot-dashboard',  userToken: this.a ]);

          





second.component.ts

import Component, OnDestroy, ErrorHandler, OnInit, ViewChild from '@angular/core';
import  NbThemeService  from '@nebular/theme';
import  takeWhile  from 'rxjs/operators' ;
import  SolarData  from '../../@core/data/solar';
import ParkingService from '../../services/parking.service';
import  Router  from '@angular/router';
import  stringify  from 'querystring';
import  Subject, BehaviorSubject  from 'rxjs';
import  HomepageComponent  from './homepage/homepage.component';

interface CardSettings 
  title: string;
  iconClass: string;
  type: string;



@Component(
  selector: 'ngx-dashboard',
  styleUrls: ['./dashboard.component.scss'],
  templateUrl: './dashboard.component.html',

  providers: [ParkingService]
)
export class DashboardComponent implements OnDestroy,OnInit 

  selectedMoments1 = new Date();
  selectedMoments2 = new Date();
  selectedMoment = new Date();
  time1 = new Date();
  time3 = new Date();
  getdata: any;
  parkingid: string;
  parkingpost: any;
  allspots: any;
  getdatadis: any;
  allspotsdis: any;
  token:string;

  constructor(private parkingService: ParkingService, private router: Router,) 




  
  ngOnInit()

    this.parkingService.getparkingDetails().subscribe(
      data=>
      
      this.getdata = JSON.parse(data.spaces_occupied_current_slot.conventional)
      this.allspots = JSON.parse(data.space_total.conventional)
      this.getdatadis = JSON.parse(data.spaces_occupied_current_slot.disabled)
      this.allspotsdis = JSON.parse(data.space_total.disabled)
    ,
    error => 
      console.error(error);

    ,
    );

  

  plus(t1,t2,selected,a)

    let plate:string = a.value;
    const a1 = t1.value.slice(0,2);
    const b1 = parseInt(a1);

    const a2=t2.value.slice(0,2);
    const b2 = parseInt(a2);



    if(selected=="general")

          for (let index: number= b1; index <=b2; index++) 

            this.parkingService.getparkingDetails().subscribe(


              data=>
              
              //this.getdata = data.spaces_occupied_current_slot.conventional
              //this.allspots = JSON.parse(data.space_total.conventional)
              //this.getdatadis = JSON.parse(data.spaces_occupied_current_slot.disabled)
             // this.allspotsdis = JSON.parse(data.space_total.disabled)
              this.parkingid = data._id
              this.parkingpost=
                "parking_site_id": this.parkingid,
                "licence_plate": plate ,
                "indexes": [index],
                "operation_type":"append",
                "spot_type": "conventional" 

              

                //this.parkingpost=JSON.parse(JSON.stringify(this.parkingpost)); 
        this.parkingService.addparkingDetails(this.parkingpost).subscribe(
          response => 
          //this.router.navigate(['/pages/dashboard']);
          window.alert("Επιτυχής ανανέωση στοιχείων");

          setTimeout(() => 
            this.parkingService.getparkingDetails().subscribe(

              data=>
              
              this.getdata = JSON.parse(data.spaces_occupied_current_slot.conventional)
              this.allspots = JSON.parse(data.space_total.conventional)
              this.getdatadis = JSON.parse(data.spaces_occupied_current_slot.disabled)
              this.allspotsdis = JSON.parse(data.space_total.disabled)
            ,
            error => 
              console.error(error);

            ,
            );
        , 3000);
        ,
        error => 

          console.error(error);




        ,
        );

              ,
              error => alert(error)
            ); 





     
      
    else
          for (let index: number= b1; index <=b2; index++) 

            this.parkingService.getparkingDetails().subscribe(


              data=>
              
              this.getdata = data.spaces_occupied_current_slot.conventional
              this.parkingid = data._id
              this.parkingpost=
                "parking_site_id": this.parkingid,
                "licence_plate": plate ,
                "indexes": [index],
                "operation_type":"append",
                "spot_type": "disabled" 

              

                //this.parkingpost=JSON.parse(JSON.stringify(this.parkingpost)); 
        this.parkingService.addparkingDetails(this.parkingpost).subscribe(
          response => 
          //this.router.navigate(['/pages/dashboard']);
          window.alert("Επιτυχής ανανέωση στοιχείων");
          setTimeout(() => 
            this.parkingService.getparkingDetails().subscribe(


              data=>
              
              this.getdata = JSON.parse(data.spaces_occupied_current_slot.conventional)
              this.allspots = JSON.parse(data.space_total.conventional)
              this.getdatadis = JSON.parse(data.spaces_occupied_current_slot.disabled)
              this.allspotsdis = JSON.parse(data.space_total.disabled)
            ,
            error => 
              console.error(error);

            ,
            );
        , 2000);
        ,
        error => 
          console.error(error);

        ,
        );

              ,
              error => alert(error)
            ); 

        

  


  

  plin(t3,selected2,b)
  
    const plate = b.value;
    const a3=t3.value.slice(0,2);
    const b3 = parseInt(a3);
    window.alert(b3);
    window.alert(plate);
    if(selected2=="general")
      this.parkingService.getparkingDetails().subscribe(


        data=>
        
        this.getdata = data.spaces_occupied_current_slot.conventional
        this.parkingid = data._id
        this.parkingpost=
          "parking_site_id": this.parkingid,
          "licence_plate": plate ,
          "indexes": [b3],
          "operation_type":"remove",
          "spot_type": "conventional" 

        

          //this.parkingpost=JSON.parse(JSON.stringify(this.parkingpost)); 
  this.parkingService.addparkingDetails(this.parkingpost).subscribe(
    response => 
    //this.router.navigate(['/pages/dashboard']);
    window.alert("Επιτυχής ανανέωση στοιχείων");
    setTimeout(() => 
      this.parkingService.getparkingDetails().subscribe(


        data=>
        
        this.getdata = JSON.parse(data.spaces_occupied_current_slot.conventional)
        this.allspots = JSON.parse(data.space_total.conventional)
        this.getdatadis = JSON.parse(data.spaces_occupied_current_slot.disabled)
        this.allspotsdis = JSON.parse(data.space_total.disabled)
      ,
      error => 
        console.error(error);

      ,
      );
  , 2000);
  ,
  error => 
    console.error(error);

  ,
  );

        ,
        error => alert(error)
      ); 


    
    else
      this.parkingService.getparkingDetails().subscribe(


        data=>
        
        this.getdata = data.spaces_occupied_current_slot.conventional
        this.parkingid = data._id
        this.parkingpost=
          "parking_site_id": this.parkingid,
          "licence_plate": plate ,
          "indexes": [b3],
          "operation_type":"remove",
          "spot_type": "disabled" 

        

          //this.parkingpost=JSON.parse(JSON.stringify(this.parkingpost)); 
  this.parkingService.addparkingDetails(this.parkingpost).subscribe(
    response => 
    //this.router.navigate(['/pages/dashboard']);
    window.alert("Επιτυχής ανανέωση στοιχείων");
    setTimeout(() => 
      this.parkingService.getparkingDetails().subscribe(


        data=>
        
        this.getdata = JSON.parse(data.spaces_occupied_current_slot.conventional)
        this.allspots = JSON.parse(data.space_total.conventional)
        this.getdatadis = JSON.parse(data.spaces_occupied_current_slot.disabled)
        this.allspotsdis = JSON.parse(data.space_total.disabled)
      ,
      error => 
        console.error(error);

      ,
      );
  , 2000);
  ,
  error => 
    console.error(error);

  ,
  );

        ,
        error => alert(error)
      ); 


      // new_conv = p.spaces_occupided.disabled[b3].remove(plate);
      //service.post(new_conv);
    
  




  private alive = true;



  //constructor(private themeService: NbThemeService,
    //          private solarService: SolarData) 
    //this.themeService.getJsTheme()
     // .pipe(takeWhile(() => this.alive))
      //.subscribe(theme => 
        //this.statusCards = this.statusCardsByThemes[theme.name];
    //);

    //this.solarService.getSolarData()
      //.pipe(takeWhile(() => this.alive))
      //.subscribe((data) => 
        //this.solarValue = data;
     // );
  //

  ngOnDestroy() 
   this.alive = false;
  



/////////////////////////////////////// ///////////////////////////////////////// ///////////////////////////////////////// //////////////////////

【问题讨论】:

【参考方案1】:

你可以使用RouterStateSnapshot从第一个组件接收数据到第二个组件 第一个在第二个组件中 **从'@angular/router'导入ActivatedRoute;

import 'rxjs/add/operator/filter';**

并创建一个路由器实例

构造函数(私有路由:ActivatedRoute) 最后使用 RouterStateSnapshot 这是您可以在代码中使用的示例

从'@angular/router'导入ActivatedRoute;进口 'rxjs/add/operator/filter';

export class LoginComponent 
    constructor(private router: Router)  

ngOnInit() this.route.queryParams .filter(params => params.order) . 订阅(参数 => 控制台.log(参数); // 订单:“流行”

    this.order = params.order;
    console.log(this.order); // popular
  );

【讨论】:

非常感谢您的回答。它打印出: RouterStateSnapshot _root: TreeNode, url: "/pages/iot-dashboard;userToken=a" 我只想打印 userToken 的值,在这个例子中是 "a"。 您也可以在角度中使用查询参数此链接为您提供使用路由器alligator.io/angular/query-parameters的丰富知识

以上是关于在Angular 2中使用传递变量进行路由?的主要内容,如果未能解决你的问题,请参考以下文章

手动传递的 Angular 路由变量在组件中未定义

不将数据从服务方法传递到猫鼬获取路由以使用 Angular IO 查询数据

Angular 1.5 父子组件问题

如何使用 Angular.js 进行重定向?

如何在Angular 2中每次路由更改时观察路由更改和布尔变量的更改值?

使用angular js通过URL传递变量