繁体   English   中英

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

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

我从index.html中的url中删除了查询参数,但是我想在app.component.html中使用这些查询参数,并使用ActivatedRoute处理我的app.component.ts,现在当我在index.html中拥有此脚本时,我的应用程序便开始了。 componen.ts也不接收那些queru参数,如何让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'];
      }     
    });
  }

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

    };
  }

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

为了使它起作用,其背后的想法是使查询参数保持服务状态。

进行一项将保存数据的服务:

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$

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM