根据教程制作代码,但我不起作用,因为即使我更改了 url,activatedRoute 参数总是空的。也许它在 Angular 12 中发生了变化,因为教程是版本 11。我来自 react,我是 Angular 的初学者并且通过选择,我会用状态而不是参数来做这个。我也遇到了另一个问题:当我
切换 url 时,'details/:id' 没有显示 DetailsComponent,例如 localhost:4200/details/15 感谢您的帮助
这是我的路由模块:
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 {}
这是我的魔法发生的组件。但是当我更改 url 时 params['sparam'] 不会改变
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();
}
}
}