为什么我无法获得服务中的数据路由

时间:2017-01-04 15:32:26

标签: angular angular2-routing angular2-services

我希望能够在服务中动态获取路由信息,但发现数据为空(例如,作为数据属性..),但它可以从组件中获取完整数据

live example



// AppRoutingModule
const routes: Routes = [
  { path: '', redirectTo: '/child', pathMatch: 'full' },
  {
    path: 'child',
    component: ChildComponent,
    data: {
      pageName: 'child page!!'
    }
  },
];
========================
// ChildComponent
export class ChildComponent implements OnInit {

  constructor(
    private activateRoute: ActivatedRoute,
    private childService: ChildService
  ) { 

  }

  getPageName() {    
    this.activateRoute.data
      .subscribe(val => console.log('child_component_pageName:', val['pageName']));
  }
  
  ngOnInit() {
    // has Data
    this.getPageName();
   // empty 
   this.childService.getPageName();
   // empty
   this.childService.getPageNameBySnapshot();

   /*
   output:
   ---
   child_component_pageName: child page!!
   child_service_pageName: undefined
   child_service_snapshot_pageName: undefined
   */
  }

}

==================================
// ChildService
@Injectable()
export class ChildService {
    constructor(private activateRoute: ActivatedRoute) {

    }

    getPageName() {
        this.activateRoute.data
        .subscribe(val => console.log('child_service_pageName:', val['pageName']));
    }

    getPageNameBySnapshot() {
         console.log('child_service_snapshot_pageName:', this.activateRoute.snapshot.data['pageName']);
    }
}




  

我的英语不好,如果语法不对,请告诉我。

0 个答案:

没有答案