【问题标题】:App only breaks when certain page set as default in Angular 2 (Chrome Only)仅当某些页面在 Angular 2 中设置为默认页面时应用程序才会中断(仅限 Chrome)
【发布时间】:2025-12-04 11:35:01
【问题描述】:

编辑:这实际上只发生在 Google Chrome 中。

我的路线是这样设置的

@RouteConfig([
  {path:'/login',           name: 'Login',       component: LoginComponent},
  {path:'/products',        name: 'Products',    component: ProductComponent,useAsDefault:true},
  {path:'/register',        name: 'Register',    component: RegisterComponent},
  {path:'/checkout',        name: 'Checkout',    component: CheckoutComponent},
  {path:'/movie/:id',       name: 'View',        component: ViewmovieComponent},
  {path:'/profile/',        name: 'Profile',     component: ProfileComponent}
])

将 /products 设置为我的默认页面时,整个应用程序似乎默默地失败了。但是,如果我将另一个页面设置为主页,它会完美运行(包括产品页面)

我在控制台中没有看到任何错误消息,因此不确定如何调试问题。我的产品组件是这样的

import {Component} from 'angular2/core';
import {ProductService} from './product.service';
import {OnInit} from 'angular2/core';
import {ROUTER_DIRECTIVES} from 'angular2/router';

@Component({
  selector    : 'product',
  templateUrl : './templates/product.tpl.html',
  directives: [ROUTER_DIRECTIVES] 
})

export class ProductComponent implements OnInit {

  public products: Product[];
  constructor(private _productService: ProductService){
    console.log('fired');
  }

  //////////

  letsGo() {
    $('html,body').animate({
      scrollTop: $('.movies').offset().top - 45
    });
  }

  getProducts(){
    this._productService.getProducts()
      .subscribe(
        data => this.products = data.message,
        error => console.log(error);
      );
  }

  ngOnInit():any{
    this.getProducts();
  }


}

任何建议都会很棒。

【问题讨论】:

  • 您的@RouteConfig() 用于已弃用的路由器。您的导入也适用于旧的 Angular2 版本。
  • public products: Product[]; 中您从哪里获得了Product 对象?

标签: javascript angular


【解决方案1】:

您是否尝试过从 / 重定向到您的产品组件,而不是设置路由默认值?也许这行得通。

例如:

@RouteConfig([
{path:'', redirectTo: '/products', pathMatch: 'full'},
{path:'/login',           name: 'Login',       component: LoginComponent},
{path:'/products',        name: 'Products',    component: ProductComponent},
{path:'/register',        name: 'Register',    component: RegisterComponent},
{path:'/checkout',        name: 'Checkout',    component: CheckoutComponent},
{path:'/movie/:id',       name: 'View',        component: ViewmovieComponent},
{path:'/profile/',        name: 'Profile',     component: ProfileComponent}

])

【讨论】:

  • 试过但结果一样!
  • 您还在使用“旧”路由器吗?尝试合并到新的?
  • 仍在使用旧的(尽管我直到在这个之上的几个 cmets 才意识到这一点)如果我不能让它工作,我会尝试合并到新的。但是,考虑到它适用于所有其他页面,显然有一些事情可以修复。
  • 我无法解释这个问题,因为我没有足够的角度经验。但似乎您也在使用旧版本的 angular2。您是否尝试过将组件复制粘贴到另一个文件中或给它另一个组件名称?
【解决方案2】:

我在初始化注入的实例时看到错误被吃掉:永远不会被报告。我的猜测是您的 ProductService 有问题。我会调查它,要么放置 console.log() 语句来查看它到达的位置,要么通过在 try { ... } catch(e) { console.error(e); } 中包围每个函数的主体(包括构造函数和从构造函数执行的任何代码)。

【讨论】:

    最近更新 更多