Angular 2在服务中获取routeParams

前端之家收集整理的这篇文章主要介绍了Angular 2在服务中获取routeParams前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想将逻辑从组件转移到服务.但我发现我无法在服务中获得routeParams.

我的组件看起来像

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

import { MyService }              from '../services/my.service';

@Component({
  moduleId: module.id,templateUrl: 'my.component.html',styleUrls: ['my.component.css']
})
export class MyComponent implements OnInit {
  constructor(private myService: MyService,private route: ActivatedRoute) {;}

  public ngOnInit() {
    this.route.params
      .subscribe((params: Params) => {
        debugger;
        console.log(params);
      });
    this.myService.getParams()
      .subscribe((params: Params) => {
        debugger;
        console.log('Return1:');
        console.log(params);
      },(params: Params) => {
        debugger;
        console.log('Return2:');
        console.log(params);
      },() => {
        debugger;
        console.log('Return3:');
    });
  }
};

我的服务看起来像

import { Injectable }                     from '@angular/core';
import { Params,ActivatedRoute }         from '@angular/router';

import { Observable }                     from 'rxjs';

@Injectable()
export class MyService {
  constructor(private route: ActivatedRoute) {;}

  public getParams(): Observable<Params> {       
    this.route.params.subscribe((params: Params) => {
      debugger;
      console.log('Service1:');
      console.log(params);
    },(params: Params) => {
      debugger;
      console.log('Service2:');
      console.log(params);
    },() => {
      debugger;
      console.log('Service3:');
    });
    return this.route.params;
  }
};

当我调试时,我可以看到params填充组件并且在服务中为空.结果就是这样

Component:
Object {param: "1"}
Service1:
Object {}
Return1:
Object {}

我正在使用Angular 2.0.0.为什么组件和服务有所不同?是否可以在服务中获得参数?

编辑:
https://github.com/angular/angular/issues/11023

我们可以将ActivatedRoute传递给组件服务.然后在服务类中订阅route.params

猜你在找的Angularjs相关文章