如何访问Angular中Route的data属性?

时间:2019-03-31 23:43:34

标签: angular

我有以下代码:

https://stackblitz.com/github/NickHodges/datademo

我正在尝试在页面上显示路线的数据。

从代码中可以看到,我已经这样声明了路径信息:

const routes: Routes = [
  {
    path: 'comp1',
    component: Comp1Component,
    data: { info: 'Data from Comp1' }
  },
  {
    path: 'comp2',
    component: Comp2Component,
    data: { info: 'Data from Comp2' }
  }
];

我已经声明了这样的组件:

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-comp1',
  templateUrl: './comp1.component.html',
  styles: []
})
export class Comp1Component implements OnInit {
  constructor(public route: ActivatedRoute) {}

  ngOnInit() {}
}

并且我正在尝试像这样访问data属性:

<p>
  comp1 works!
</p>
<p>Comp1Data: {{ route.data['info'] }}</p>

所以我去了/comp1路线,但是没有显示数据。

如何在data上显示Route属性?

1 个答案:

答案 0 :(得分:3)

ActivatedRoute上的数据属性是Observable,您需要订阅它。

comp-1.component.ts

export class Comp1Component implements OnInit {

  public data;   

  constructor(public route: ActivatedRoute) {}

  ngOnInit() {
    this.route.data.subscribe(data => this.data = data);
  }

}

comp1-component.html

<p *ngIf="data">Comp1Data: {{ data.info }}</p>
  

https://angular.io/api/router/ActivatedRoute#data

     

https://stackblitz.com/edit/github-4p1j6c