I have created a single page mortgage calculator application in Angular 2, which acts like a learning playground for me (trying to get more accustomed to technology stack currently used at work)... It's running at http://www.mortgagecalculator123.com if you want to look at it. I've made it open source with a Fork Me link right on the page if you want to look at it.
Anyhow, what I want to do, is to be able to pass variables to my app, straight from the URL, so they can be consumed by my Angular 2 app. Something like this: http://www.mortgagecalculator123.com/?var1=ABC&var2=DEF
I've tried following, in my app.component.ts, I've added following:
import { Router, ActivatedRoute, Params } from '@angular/router';
AppComponent {
private var1: string;
private var2: string;
constructor(
private route: ActivatedRoute,
private router: Router
) {}
ngOnInit() {
this.route.params.forEach((params: Params) => {
this.var1 = params['var1'];
this.var2 = params['var2'];
});
console.log(this.var1, this.var2);
}
...
}
But this won't work, when I run npm start, I get following error:
aot/app/app.component.ngfactory.ts(45,30): error TS2346: Supplied parameters do not match any signature of call target.
Thank you, any help would be much appreciated.
I created a pull request with the query params working. I will try to explain everything I did.
The reason why the previous answers doesn't work is because you aren't using the router at all. You created a massive app component without routes. To fix that we need to start using the route module, I also advise you to read these two tutorials: Routing and Routing & Navigation.
First we need to change your
index.html
, add this to your<head>
:See here why it's important to add that.
Then since you are using your
AppComponent
to show everything we need to create a new component, which we will callRootComponent
. On yourindex.html
change<my-app>
to<root>
; it will look like this:Now inside your
app
folder we need to create two files the first one will beroot.component.ts
which will look like this:Look that we have the
<router-outlet></router-outlet>
as a template, Angular will inject our components based on the route.We still need to create one more file, which will be
main.route.ts
, this is what it looks like:In this file we are saying that for our base route, we want to render our
AppComponent
We have created our new files, now we need to tell our App Module about them, in your
app.module.ts
so we import the new files and declare the new component. We also need to change our boostrap component:Now with all this in place we can now finally start passing parameters to our app, on your
AppComponent
import theRouter
,ActivatedRoute
and theParams
from@angular/router
so yourAppComponent
will look something like this:You can see the pull request here
It seems you are dealing with Queryparams . So to access them, you can try below code,