Reputation: 617
I have Single sign on in place but for testing I want to read the values from the url localhost:4200/?id=test&name=testing&[email protected]
and pass them to an API in app component.
there will be a flag on which basis I will reading from url instead of using single sign on function
if (url_enabled == true) {
getParamsFromUrl()
} else {
singleSignOn()
}
I tried ActivatedRoute but it doesn't seem to be working.
I have tried queryParams, params, url, queryParamsMap
but none of these seems to be working. all I get is empty value.
inside app component
app.component.ts
getParamsFromUrl() {
this._router.events.subscribe((e) => {
if (e instanceof NavigationEnd) {
console.log(e.url)
}
})
}
this.route.queryParams.subscribe(params => {
console.log(params);
})
app.component.html
<router-outlet></router-outlet>
app-routing.module.ts
const routes: Routes = [
{path:'*/:id', component: AppComponent},
];
I have tried whatever I could found on stackoverflow or other blogs. Can somebody point out what am I missing here?
Upvotes: 14
Views: 40379
Reputation: 21
Try this one ; )
Front-end
import { Component, OnDestroy, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Subscription } from 'rxjs';
@Component({
selector: 'app-edit-category',
templateUrl: './edit-category.component.html',
styleUrl: './edit-category.component.css'
})
export class EditCategoryComponent implements OnInit, OnDestroy{
id: string | null = null;
paramsSubscription? : Subscription;
constructor(private route: ActivatedRoute) {
}
ngOnInit(): void {
this.paramsSubscription = this.route.paramMap.subscribe({
next: (parms) => {
this.id = parms.get('id');
}
});
}
ngOnDestroy(): void {
this.paramsSubscription?.unsubscribe();
}
}
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { CategoryListComponent } from './features/category/category-list/category-list.component';
import { AddCategoryComponent } from './features/category/add-category/add-category.component';
import { EditCategoryComponent } from './features/category/edit-category/edit-category.component';
const routes: Routes = [
{
path: 'admin/categories',
component: CategoryListComponent
},
{
path: 'admin/categories/add',
component: AddCategoryComponent
},
{
path: 'admin/categories/:id',
component: EditCategoryComponent
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
<td> <a href="" class="btn btn-secondary" [routerLink]="['/admin/categories',item.id]"> Edit </a> </td>
getCategoriyById(id : string): Observable<CategoryModel> {
return this.http.get<CategoryModel>(`${environment.apiBaseUrl}/api/categories/${id}`);
}
Backend
[HttpPost]
[Route("{id:Guid}")]
public async Task<IActionResult> GetCategoryById([FromRoute] Guid id)
{
var response = await iCategoryRepo.GetById(id);
if(response is null)
{
return NotFound();
}
var categoryDTO = new CategoryDto
{
Id = response.Id,
Name = response.Name,
UrlHandle = response.UrlHandle
};
return Ok(categoryDTO);
}
Upvotes: -1
Reputation: 20102
You can try like this
constructor(
private activatedRoute: ActivatedRoute
)
ngOnInit() {
this.activatedRoute.paramMap.pipe(
tap(() => console.log(this.activatedRoute.snapshot.paramMap.get(
"id"
)))
).subscribe()
}
Upvotes: 0
Reputation: 1257
Using Transition
from @uirouter/core
makes it easy to get params from url.
import {Transition} from '@uirouter/core';
@Component()
export class MyComponent {
public myParam = this.transition.params().myParam;
public constructor(public transition: Transition) {}
}
Upvotes: 0
Reputation: 5470
For this route: You can try this way:
const routes: Routes = [
{path:'*/:id', component: AppComponent},
];
In AppComponent .ts file:
constructor(
private activatedRoute: ActivatedRoute,
) { }
ngOnInit() {
this.activatedRoute.params.subscribe(params => {
const id = params['id'];
console.log('Url Id: ',id);
}
OR
ngOnInit() {
this.activatedRoute.queryParams.subscribe(params => {
const id = +params.id;
if (id && id > 0) {
console.log(id);
}
});
}
Upvotes: 12
Reputation: 139
first of all there is an url with queryParams like yours :
localhost:4200/?id=test&name=testing&[email protected]
in this way tou get to the queryparams with ActivatedRoute object lik :
this.name = this.activatedRoute.snapshot.queryParamMap.get('name'); // this.name = 'testing'
Or :
this.activatedRoute.queryParams.subscribe(params => {
this.name= params['name'];
});
and the other way is
localhost:4200/test/testing/[email protected]
you use for sync retrieval (one time) :
this.name = this.activatedRoute.snapshot.ParamMap.get('name');
Upvotes: 10
Reputation: 617
I used jquery inside angular 8 and got the href using jquery $ variable after declaring it in app component.
import { query } from '@angular/animations';
declare var $: any;
Upvotes: -7
Reputation: 689
You need to create a new component and update the routing configuration as follows:
First, create a new component: MainComponent
:
import { Component } from '@angular/core';
@Component({
selector: 'main',
template: `<router-outlet></router-outlet>`,
})
export class MainComponent {
constructor() { }
}
Then, update your AppModule
:
import { AppComponent } from './app.component';
import { MainComponent } from './main.component';
@NgModule({
imports: [
BrowserModule,
FormsModule,
RouterModule.forRoot([
{path: '', component: AppComponent}
])
],
declarations: [ MainComponent, AppComponent ],
bootstrap: [ MainComponent ]
})
export class AppModule { }
Finally, you'll need to update your index.html
file(Make sure to load the brand new component instead of the AppComponent
):
<main>loading</main>
Now you'll be able to read your parameters as requested in your AppComponent
:
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
params: Params;
constructor(private route: ActivatedRoute){}
ngOnInit() {
this.route.queryParams.subscribe((params: Params) => {
this.params = params;
console.log('App params', params);
const id = params['id'];
console.log('id', id);
});
}
}
See a working example here: https://read-params-app-component.stackblitz.io/?id=test&name=testing&[email protected].
And find the source code here.
I hope it helps!
Upvotes: 5
Reputation: 237
Angular comes us with the ActivatedRoute object. We can access the URL parameter value in same way its done above with little difference. Data in this type can be accessed with two different ways. One is through route.snapshot.paramMap and the other is through route.paramMap.subscribe. The main difference between the two is that the subscription will continue to update as the parameter changes for that specific route.
ngOnInit() {
this.route.paramMap.subscribe(params => {
this.userType = params.get("userType")
})
}
Upvotes: 4