问题描述
我在顶部导航栏中添加返回主页按钮时遇到一些问题。 我希望它将页面重置为页面的初始状态。
这是我的header.component.html,我要在其中实现返回首页的功能。
<div class="topnav">
<a class="active" routerLink="">{{title}}</a>
</div>
我尝试路由到首页,但是页面重复了(两次显示相同的组件),现在我不该做什么。我的页面也无法刷新,因为我正在做这件事,并且其中一项要求是拥有完整的SPA。我也尝试过功能destroyPlataform()
,然后导航回到path=" "
,该功能可以正常工作,但是当我这样做时页面会刷新,并且页面上无法刷新。
我的app-routing.module:
import { NgModule } from '@angular/core';
import { Routes,RouterModule } from '@angular/router';
import { MoviesComponent } from './movies/movies.component';
const routes: Routes = [{ path: '',component: MoviesComponent }];
@NgModule({
imports: [RouterModule.forRoot(routes)],exports: [RouterModule],})
export class AppRoutingModule {}
我正在使用The Movie DB API,并且在我的页面中有一些卡片,它可以搜索电影,显示这些卡片的多个页面,并且我需要此主页按钮才能返回首页或退出搜索结果。
我只有两个组件,header.component具有用于重置页面的当前状态并返回到初始状态(不起作用)的按钮,而movies.component具有显示电影卡的功能,可按名称搜索电影并有分页。我需要返回主页功能来重置搜索名称并返回到应用程序的初始状态。
有关我如何播放电影的更多信息:
movies.component.ts:
//Showing page on application and redirection
getMovies(page: number) {
this.moviesService
.getMovies(this.movieName,this.currentPage)
.subscribe((paramName) => {
page = this.currentPage;
if (this.movieName) {
this.searchMovies(this.movieName,this.currentPage);
}
if (page) {
this.currentPage++ || this.currentPage--;
}
this.totalPages = (paramName as any).total_pages;
this.movies = (paramName as any).results;
});
}
//Search functions bellow
//search by query
searchMovies(query: string,page: number) {
this.moviesService.searchMovies(query,page).subscribe((response) => {
query = this.movieName;
page = 1;
this.totalResults = (response as any).total_results;
this.movies = [];
this.movies = response['results'];
});
}
//send value of query to the search function
queryListener(value: string): void {
this.movieName = value;
this.currentPage = 1 + 1;
this.searchMovies(value,1);
}
//End of search functions
movies.service.ts:
//Redirects
getMovies(query: string = '',page: number) {
if ((query = '')) {
return this.discoverMovies(page);
}
if (query) {
return this.searchMovies(query,page);
}
return this.discoverMovies(page);
}
下一个方法也位于movie.service.ts中,当我单击主页按钮时,我想回到他那里查看发现卡
//Show the list of movies more recent by popularity
discoverMovies(page: number) {
let discover = `${this.discoverUrl}?api_key=${this.apiKey}&language=${this.language}&sort_by=popularity.desc&include_adult=false&include_video=false&page=${page}`;
return this.http.get(discover);
}
一个简单的'href="localhost:4200/"
'会有所帮助,但是当我使用href
时,页面会刷新。我希望有人能帮助我!
解决方法
尝试使用:
<div class="topnav">
<a class="active" [routerLink]="['/']">{{title}}</a>
</div>