首页 文章

当我刷新页面时Angular2,而不是页面加载路由器参数

提问于
浏览
1

我的应用程序通常在所有路由器中加载但是当我使用带有params的路由器时,应用程序无法加载 .

示例: localhost:3000/usersid/:id

路由器代码是:

const appRoutes: Routes = [
  { path: 'user', component: UserComponent },
  { path: 'info', component: InfoComponent },
  { path: 'users', component: UsersComponent },
  { path: 'usersid/:id', component: UsersIdComponent },
  { path: '', component: MainComponent },
  { path: '**', component: MainComponent }
];

和params路由器的组件

import{Component} from '@angular/core'
import { ActivatedRoute } from '@angular/router';
import * as Datastore from 'nedb';

@Component({
  moduleId : module.id ,
  templateUrl : 'userid.component.html' ,
  styles : [`
    .SamRouter {
        overflow-y: auto;
    }
    `]
})

export class UsersIdComponent {
  id: any;
  private sub: any;
  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
      this.sub = this.route.params.subscribe( params  => {
      // this.id = +params['id']; // (+) converts string 'id' to a number
      this.id = params['id'] || 0 ;

        // In a real app: dispatch action to load the details here.
     });
        console.log(  this.id )
   }
   ngOnDestroy() {
    //  this.sub.unsubscribe();
    }

}

错误信息:

http:// localhost:3000 / users / node_modules / bootstrap / dist / js / bootstrap.min.js无法加载资源:服务器响应状态为404(未找到)http:// localhost:3000 / users /styles.css无法加载资源:服务器响应状态为404(未找到)

2 回答

  • 0

    这取决于您使用的服务器 . 您需要将服务器配置为在路由不存在时转到index.html . 当您按F5服务器搜索不存在的文件时,服务器应该返回index.html,然后角度路由器将完成其余的工作 .

  • 1

    改变这个:

    const appRoutes: Routes = [
      { path: 'user', component: UserComponent },
      { path: 'info', component: InfoComponent },
      { path: 'users', component: UsersComponent },
      { path: 'usersid/:id', component: UsersIdComponent },
      { path: '', component: MainComponent },
      { path: '**', component: MainComponent }
    ];
    

    对此:(注意Routes数组中的第四个元素)

    const appRoutes: Routes = [
      { path: 'user', component: UserComponent },
      { path: 'info', component: InfoComponent },
      { path: 'users', component: UsersComponent },
      { path: 'users/:id', component: UsersIdComponent },
      { path: '', component: MainComponent },
      { path: '**', component: MainComponent }
    ];
    

相关问题