A make a code according to a tutorial but me doesnt work because the activatedRoute params always empty even though i change the url.Maybe its changed in Angular 12 because the the tutorial was in version 11.Im comming from react and i am beginner with Angular and by choice i would make this with states not params.
And i had an other problem as well: 'details/:id' doesnt show up the DetailsComponent when i
toggle an url for example like this localhost:4200/details/15
Thanks for the help
this is my routing modul:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { DetailsComponent } from './components/details/details.component';
import { HomeComponent } from './components/home/home.component';
const routes: Routes = [
{
path: '',
component: HomeComponent,
},
{
path: 'search/:sparam',
component: HomeComponent,
},
{
path: 'details/:id',
component: DetailsComponent,
},
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
})
export class AppRoutingModule {}
And this my component where the magic would happen.But the params['sparam'] doesnt change when i change the url
import { Component, OnDestroy, OnInit } from '@angular/core';
import { ActivatedRoute, Params, Router } from '@angular/router';
import { Subscription } from 'rxjs';
import { APIResponse, Game } from '../../model/model';
import { HttpService } from 'src/app/services/http.service';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss'],
})
export class HomeComponent implements OnInit, OnDestroy {
public sort: string;
public games: Array<Game>;
private routeSub: Subscription;
private gameSub: Subscription;
public str: string;
constructor(
private httpService: HttpService,
private router: Router,
private route: ActivatedRoute
) {}
ngOnInit(): void {
this.routeSub = this.route.params.subscribe((params: Params) => {
if (params['sparam']) {
this.searchGames('-added', params['sparam']);
console.log(params['sparam']);
} else {
this.searchGames('-added');
console.log(params['sparam']);
}
});
}
searchGames(sort: string, search?: string): void {
this.gameSub = this.httpService
.getGamesList(sort, search)
.subscribe((gameList: APIResponse<Game>) => {
this.games = gameList.results;
console.log(this.games);
});
}
openGameDetails(id: number): void {
this.router.navigate(['details', id]);
}
ngOnDestroy(): void {
if (this.gameSub) {
this.gameSub.unsubscribe();
}
if (this.routeSub) {
this.routeSub.unsubscribe();
}
}
}