Маршрутизация с передачей переменной в Angular 2? - PullRequest
0 голосов
/ 08 апреля 2020

У меня есть два компонента. Во-первых, я получаю входное значение и хочу направить второй компонент, передавая входное значение с помощью. Во втором компоненте я хочу напечатать это входное значение.

first.component. html

<code><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>

    
 Είσοδος    

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 Ответ

0 голосов
/ 08 апреля 2020

получить данные от первого компонента ко второму компоненту, который вы можете сначала использовать RouterStateSnapshot во втором компоненте ** import {ActivatedRoute} из '@ angular / router';

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

и создайте экземпляр конструктора Router

(частный маршрут: ActivatedRoute)
и последнее использование RouterStateSnapshot
, вот пример вы можете использовать в своем коде

import {ActivatedRoute} из '@ angular / router'; import 'rxjs / add / operator / filter';

export class LoginComponent {
    constructor(private router: Router) { }

ngOnInit () {this.route.queryParams .filter (params => params.order) .subscribe (params => {console.log ( params); // {заказ: "популярный"}

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