如何将静态数据从路由配置传递到组件

时间:2018-06-20 11:32:05

标签: angular angular2-routing

我需要将静态数据从路由传递到组件。我尝试在路由配置中传递数据,但是当我从ActivatedRoute订阅数据时得到空数据。我在下面提供了我的代码

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { RouterModule, Routes } from '@angular/router';
import { AppComponent } from '../../app.component';
import { CompanyInformationComponent } from '../../components/pages/company/company-information/company-information.component';
import { CompanyDescriptionComponent } from '../../components/pages/company/company-description/company-description.component';

const routes: Routes = [
  { path:'', redirectTo: 'company-information', pathMatch: 'full', data: { title: 'Company Information' } },
  { path:'company-information', component: CompanyInformationComponent, data: { title: 'Company Information' } },
  { path:'company-description', component: CompanyDescriptionComponent, data: { title: 'Company Description' } },
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [
    RouterModule
  ],
  providers: [

  ]
})
export class routingModule { }

我的标题组件

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

import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'site-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {

  constructor( private route:ActivatedRoute ) {

  }

  ngOnInit() {
    this.route.data.subscribe(
      data => {
        console.log('Title',data);
      }
    )
  }
}

2 个答案:

答案 0 :(得分:0)

您可以使用route.snapshot.data

获取数据

您还应该注入Router来注意router.events,以便构造函数看起来像

constructor (private router : Router, private route : ActivatedRoute) {}

和OnInit

ngOnInit() {
    this.router.events
        .filter(event => event instanceof NavigationEnd)
        .subscribe(
            () => {
                console.log(this.route.snapshot.data) // should print { title: 'Company Information'}
            }
    );
}

答案 1 :(得分:0)

您可以像这样简单地通过路由传递值:

示例:path: 'company-information/:valueToPass',

在您的组件中:

import { ActivatedRoute } from '@angular/router';

[...]

constructor( protected route: ActivatedRoute){
 this.route.params.subscribe((params) => {
      if (params.valueToPass) {
        this.localValue= params.valueToPass;
      }
    });
}