我正在尝试从url提取查询参数
https://localhost:8080/myapp/shared?id1=2&id2=4
我需要使用
id1
和
id2
my中的值
app.component.ts
.我正在尝试使用
Router, ActivatedRoute, Params from '@angular/router'
但当我运行应用程序时,主页未加载,我在浏览器控制台中看到以下错误:
Error: StaticInjectorError[t]:
StaticInjectorError[t]:
NullInjectorError: No provider for t!
Stack trace:
LMZF/</yi</t.prototype.get@http://localhost:8081/myapp/main.a7059837ce4dd4ad4d9f.bundle.js:1:293926
y/<@http://localhost:8081/myapp/main.a7059837ce4dd4ad4d9f.bundle.js:1:237630
y@http://localhost:8081/myapp/main.a7059837ce4dd4ad4d9f.bundle.js:1:237237
这是我的
应用程序。组成部分ts
看起来像:
import { Component, Input, OnInit } from '@angular/core';
import { HeaderComponent } from './header/header.component';
import {Router, ActivatedRoute, Params} from '@angular/router';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
constructor(private activatedRoute: ActivatedRoute) {}
ngOnInit() {
this.activatedRoute.params.subscribe((params: Params) => {
let userId = params['id1'];
console.log("parameter is: "+ userId);
});
}
title = 'My First Angular App';
}
问题是,我补充道
Router
导致错误的代码,甚至没有加载上述url。当我尝试在没有查询参数代码的情况下运行应用程序时,它运行得很好。
已从尝试此解决方案
this answer
.还调查了另一个
similar question
但这没有帮助。
有人能解释为什么会这样吗?
使现代化
已在中添加以下导入语句
app.module.ts
:
imports: [
BrowserModule,
HttpModule,
RouterModule.forRoot([{
path: '',
component: AppComponent
},
])
现在,这使得应用程序加载,但仍然没有提取参数。浏览器控制台上出现以下错误:
Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'shared'
更新2
为各个url添加路由路径可以解决控制台错误问题,但我的参数仍然未定义。
RouterModule.forRoot([{
path: '',
component: AppComponent
},
{
path: 'shared',
component: AppComponent
},
])