Fariba
Fariba

Reputation: 723

removing url in index.html but how can i have them in app.component.ts

I removed query params from url in index.html, but i want in app.component.html work with those query params, and my app.component.ts using ActivatedRoute, Now when i have this script in index.html then my app.componen.ts also does not receive those queru params, how can i let app.component.ts have my query params?

this is my script in my index.html to remove query params:

    <script type="text/javascript">
    var url = window.location.toString();
   if(url.indexOf("?") > 0) {
      var sanitizedUrl = url.substring(0, url.indexOf("?"));
      window.history.replaceState({}, document.title, sanitizedUrl);
    }
  </script>

and this is my app.component.ts to pars query params:

import {ApiService} from './api.service';
import {Component, OnInit} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {Converter} from './converter';
import {Title} from '@angular/platform-browser';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  username = '';
  department = '';

   json;
  constructor(
    private feedbackService: ApiService,
    private titleService: Title,
     private route: ActivatedRoute
    ) {
  }

  ngOnInit() {
    this.route.queryParams.subscribe(params => {
      if (params.hasOwnProperty('username')) {
        this.username = params['username'];
      }     
      if (params.hasOwnProperty('department')) {
        this.department = params['department'];
      }     
    });
  }

Upvotes: 0

Views: 466

Answers (2)

Nikola Stekovic
Nikola Stekovic

Reputation: 635

After some research, there's no clear cut solution for it but still, I did manage to create some solution that should work.

Idea behind it in order to make it works is to keep query params in service.

Make a service that will hold the data:

import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class SampleService {
  data: BehaviorSubject<any> = new BehaviorSubject({});
  data$: Observable<any> = this.data.asObservable();
}

afterwards, in your app.component.ts

constructor(
    private activatedRoute: ActivatedRoute,
    private router: Router,
    private sampleService: SampleService
  ) {}

  ngOnInit(): void {
    this.sampleService.data$.subscribe(console.log);
    this.activatedRoute.queryParams.subscribe((data: {username: string, departure: string}) => {
      if(data.hasOwnProperty('username') || data.hasOwnProperty('departure')) {
        this.sampleService.data.next(data);
      }
      setTimeout(() => { // note this timeout is mandatory and it makes this kinda cheatfix the whole thing
        this.router.navigateByUrl('/');
      });
    });
  }

in this way, you'll have your params kept in SampleService's data behaviour subject. If you want to use it somewhere, all you have to do is inject service, and subscribe to data$.

Please note, this solution contains few subscriptions that should be handled carefully but not this question's topic.

Small short demo can be found here. Check demo console when you open stackblitz app with queryParams as /?username=foo.

Upvotes: 1

rmrouse88
rmrouse88

Reputation: 291

Could you not just place those query parameters into session storage and then access session storage inside app.component.ts?

  <script type="text/javascript">
    var url = window.location.toString();
   if(url.indexOf("?") > 0) {
      var [ sanitizedUrl, queryParams ] = url.split('?')
      window.history.replaceState({}, document.title, sanitizedUrl);
      sessionStorage.setItem('params', queryParams)
    }
  </script>
//app.component.ts

export class AppComponent implements OnInit {
  username = '';
  department = '';

   json;
  constructor(
    private feedbackService: ApiService,
    private titleService: Title,
     private route: ActivatedRoute
    ) {
  }

  ngOnInit() {
    let params = sessionStorage.getItem('params');
    // parse params logic here // 

    if (params.hasOwnProperty('username')) {
        this.username = params['username'];
      }     
      if (params.hasOwnProperty('department')) {
        this.department = params['department'];
      }     

    };
  }

Upvotes: 3

Related Questions