Problem with the observable route.queryParams

2

Good, what I try to do is pass 2 values within an array from one component to another, and receive them in the ngOnInit() function of the child component.

The way I send them from component1 is as follows:

HTML

<button class="boton" type="button" (click)="navegar()"></button>

TS

navegar = function () {
   let parametros: any[] = [];
   parametros.push(this.var1);
   parametros.push(this.var2)
   this.router.navigate(['/componente2'], { queryParams: { array: parametros} });
}

And I receive them like this:

TS

ngOnInit() {
   this.route.queryParams
     .subscribe(params => {
       if (params !== {} && params.array[0] === "true") {
         this.varAux = params.array[1];
       }
     })
}

What happens is that when I access component2 without having navigated from component1 , but from another side of the application and ngOnInit() is executed, I receive params = {} .

  

I can not find a way to validate that this object is empty so,   that does not enter the if else condition.

Since which property of the queryParams DOM can I validate so that I do not subscribe directly if parameters do not arrive?

    
asked by Joaquin Diaz 04.10.2017 в 18:03
source

2 answers

0

The problem with your comparison is that you are creating an object and then asking if it is the same as the one received, which will always return false.

let a={};
let b={};
console.log(a==b)

If you want to check if there is an attribute, in this case array, just do it like this:

let p= {
  array: ['test',true]
}

function test(p) {
  if (p && p.array) {
    console.log(p.array[0]);
  } else {
    console.log('No encontrado');
  }
}

test(p);
test({})
    
answered by 04.10.2017 в 18:35
0

What I did was parse a string the subscribe response and validate its length

ngOnInit() {
  this.route.queryParams
    .subscribe((params: any) => {
      let aux: string = JSON.stringify(params)
      if (aux.length > 2 && params.array[0] === "true") {
        this.varAux = params.array[1];
      }
   })
}

Still open to a solution to validate prior to subscribing to the queryParams, to know if there is a property of the observable that tells me if I receive parameters or not from the navigation

    
answered by 05.10.2017 в 18:45