我想将逻辑从组件转移到服务.但我发现我无法在服务中获得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.为什么组件和服务有所不同?是否可以在服务中获得参数?
我们可以将ActivatedRoute传递给组件服务.然后在服务类中订阅route.params
原文链接:https://www.f2er.com/angularjs/240406.html