【问题标题】:Changes in angular 2 urls after reload重新加载后 angular 2 url 的变化
【发布时间】:2016-10-29 09:29:41
【问题描述】:

我的 Angular 2 应用程序中有 queryParams 和 params 的网址。我遇到了一个问题:重新加载页面后,我的网址失真了。

params:

http://127.0.0.1:8000/albums?user_id=1

重新加载后:

http://127.0.0.1:8000/albums/?user_id=1

queryParams:

http://127.0.0.1:8000/albums/%3Aid;id=13

重新加载后:

http://127.0.0.1:8000/albums/%3Aid%3Bid%3D13

routes.ts

import { ModuleWithProviders }  from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { HomeComponent } from './components/home/home.component';
import { LoginComponent }  from './components/login/login.component';
import { RegisterComponent }  from './components/register/register.component';
import { AlbumsComponent }  from './components/albums/albums.component';
import { AddAlbumComponent }  from './components/albums/add-album.component';
import { AddImageAlbumComponent }  from './components/albums/add-image-album.component';
import { AlbumDetailComponent }  from './components/albums/album-detail.component';
import { PhotosComponent }  from './components/photos/photos.component';
import { UsersComponent }  from './components/users/users.component';
import { AuthGuard } from './guards/auth.guard'

const appRoutes: Routes = [
    { path: '', component: HomeComponent },
    { path: 'login', component: LoginComponent },
    { path: 'register', component: RegisterComponent },
    { path: 'albums', component: AlbumsComponent, canActivate: [AuthGuard] },
    { path: 'add-album', component: AddAlbumComponent, canActivate: [AuthGuard] },
    { path: 'add-image-album/:id', component: AddImageAlbumComponent, canActivate: [AuthGuard] },
    { path: 'albums/:id', component: AlbumDetailComponent, canActivate: [AuthGuard] },
    { path: 'photos', component : PhotosComponent, canActivate: [AuthGuard] },
    { path: 'users', component : UsersComponent, canActivate: [AuthGuard] }
];

export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);

使用params导航:

[routerLink]="['/albums/:id', {id: album.id}]

使用queryParams导航:

[queryParams]="{user_id: dataService.getCurrentUserId()}"

【问题讨论】:

  • 您的导航代码似乎有问题。你能在你处理导航的地方展示你的组件吗?
  • 我也有同样的问题。

标签: angular angular2-routing


【解决方案1】:

在 url 解码你重新加载的 queryparams url 之后,我得到了这个:

http://127.0.0.1:8000/albums/:id;id=13

它与您的原始 url 基本相同,但参数完全 url 编码。

更新:

如果您需要有关如何强制解码 url 的参考,您可以查看this previous stack overflow question

【讨论】:

    【解决方案2】:

    在 RouteLink 本身中传递参数,例如,请参见下面的代码

    [routerLink]="[/albums,nav.param]"
    

    并且在路由中这样声明

    { path: 'albums/:id', component: AlbumsComponent }
    

    并且在 albumscomponent.ts 中使用 activateroute 读取 url 参数值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-16
      • 2017-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-20
      • 1970-01-01
      相关资源
      最近更新 更多