【问题标题】:Angular 2 on refresh binding is undefined刷新绑定上的 Angular 2 未定义
【发布时间】:2016-04-05 21:37:47
【问题描述】:

应用组件:

@RouteConfig([
  {path:'/', name: 'Dashboard', component: DashboardComponent, useAsDefault: true},
  {path:'/model/:id', name: 'ModelDetail', component: ModelDetailComponent},
])

访问者直接访问: http://localhost:8080/model/4

在渲染“ModelDetailComponent”之前,我们需要在 ngOnInit() 类中加载所有模型。

ngOnInit() {
    let id = parseInt(this.routeParams.get('id'));
    this.modelService.subject$.subscribe(models => {
      if ( models.length > 0 ) {
        this.model = models[0];
      }
    })
    this.modelService.getModel(id);
  }

模板:

<h1>{{model.name}}</h1>
<model-list [model]="model"></model-list> //nested compnent that also use the model.

财产

public model:IModel;

【问题讨论】:

    标签: angular angular2-template


    【解决方案1】:

    我认为您正在寻找的是CanActivate 钩子。它将允许您等待组件渲染,直到数据被解析(类似于 Angular 1.x 的解析功能)。

    更多详情请见this

    【讨论】:

    • 是的,它会等待页面加载,直到数据到达,我想这首先是你的问题,对吧?
    • @JamalJames 很酷,如果解决了您的问题,请将我的解决方案标记为答案
    • 我刚刚做了@YanivEfraim
    • @JamalJames 酷!您可以标记“V”符号,这样人们就会知道这是您的正确答案(:
    【解决方案2】:

    随便用

    <h1>{{model?.name}}</h1>
    

    (添加?)那么数据稍后到达并不重要。

    如果你有很多这样的绑定,用*ngIf包装整个模板可能会更容易

    @Component({
      selector: 'my-component',
      template' `
        <div *ngIf="model">
          <h1>{{model.name}}</h1>`})
        <div>
    class MyComponent {  }
    

    【讨论】:

    • 我猜是这样,但如果不能重现,这很困难。如果您可以提供 Plunker,我可以验证这是否真的可以解决您的问题。目前这只是一个猜测。
    • 你试过我的建议了吗?
    • 它有效,但问题是我必须在“RouteConfig”上用于特定 URL 的每个组件上执行此操作!
    • 问题是每个组件在渲染组件之前都需要json文档。所以我必须明确地将“if switch”添加到每个组件。
    • 我认为这仍然是使您的组件异步兼容的最佳方式。通常不是每个异步调用都是由导航和路由更改引起的。
    猜你喜欢
    • 1970-01-01
    • 2021-09-22
    • 1970-01-01
    • 2023-03-28
    • 2019-05-05
    • 2017-01-28
    • 2018-02-25
    • 2021-01-20
    • 1970-01-01
    相关资源
    最近更新 更多