我从index.html中的url中删除了查询参数,但我想在app.component.html中使用这些查询参数,并且我的app.component.ts使用ActivatedRoute, 现在,当我在index.html中有这个脚本时,我的app.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'];
}
});
}
最佳答案
您是否可以将这些查询参数放入 session 存储中,然后访问 app.component.ts 中的 session 存储?
<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'];
}
};
}
关于javascript - 删除index.html中的url,但我怎样才能将它们放在app.component.ts中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56621788/