Angular 2在服务中获取routeParams

Tho*_*lik 7 angular2-routing angular2-services angular

我想将逻辑从组件转移到服务.但我发现我无法在服务中获得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:');
    });
  }
};
Run Code Online (Sandbox Code Playgroud)

我的服务看起来像

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;
  }
};
Run Code Online (Sandbox Code Playgroud)

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

Component:
Object {param: "1"}
Service1:
Object {}
Return1:
Object {}
Run Code Online (Sandbox Code Playgroud)

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

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

jua*_*827 6

根据这一点,你必须遍历路由树并从树底部的路线获取数据.

@Injectable()
export class MyService{

  constructor(private router:Router,private route:ActivatedRoute){   
   this.router.events
    .filter(event => event instanceof NavigationEnd)
     .subscribe((event) => {
         let r=this.route;
         while (r.firstChild) {
            r = r.firstChild
        }
         //we need to use first, or we will end up having
         //an increasing number of subscriptions after each route change.   
         r.params.first().subscribe(params=>{                
           // Now you can use the params to do whatever you want
         });             


    });            
  }
}
Run Code Online (Sandbox Code Playgroud)


小智 4

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

  • 是的,我现在就是这样做的。但这是一个解决方法。这样我们就在组件中拥有了逻辑,并且我们必须将这个逻辑实现到我想要使用此服务的每个组件中。为什么在服务中不可能呢? (2认同)
  • “*我想将逻辑从组件转移到服务*” (2认同)