删除index.html中的url,但是如何在app.component.ts中使用它们

时间:2019-06-16 19:01:06

标签: javascript angular

我从index.html中的url中删除了查询参数,但是我希望在app.component.html中使用这些查询参数,并使用ActivatedRoute处理我的app.component.ts, 现在,当我在index.html中拥有此脚本时,我的app.componen.ts也不会收到那些队列参数,如何让app.component.ts具有查询参数?

这是我index.html中的脚本,用于删除查询参数:

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

这是解析查询参数的我的app.component.ts:

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'];
      }     
    });
  }

2 个答案:

答案 0 :(得分:3)

您不仅可以将这些查询参数放入会话存储中,然后访问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'];
      }     

    };
  }

答案 1 :(得分:1)

经过研究,目前尚无明确的解决方案,但我确实设法创建了一些可行的解决方案。

要使其有效,其背后的想法是使查询参数保持服务状态。

提供将保留数据的服务:

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();
}

然后,在您的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('/');
      });
    });
  }

通过这种方式,您可以将参数保存在SampleService的数据行为主题中。如果您想在某个地方使用它,您要做的就是注入服务,并订阅data$

请注意,此解决方案包含一些应谨慎处理的订阅,但不是此问题的主题。

可以找到小型的简短演示here。当您打开带有queryParams作为/?username = foo的stackblitz应用程序时,请检查演示控制台。