Angular 2 在服务中获取 routeParams [英] Angular 2 get routeParams in a service
本文介绍了Angular 2 在服务中获取 routeParams的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将逻辑从组件转移到服务.但是我发现我无法在服务中获取 routeParams.
I want to shift the logic from component to service. But I found out that I can't get the routeParams in a service.
我的组件看起来像
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;
}
};
当我调试时,我可以看到参数在组件中填充并在服务中为空.结果就是这样
When I debug I can see that params are filled in component and empty in service. That's the result
Component:
Object {param: "1"}
Service1:
Object {}
Return1:
Object {}
我使用的是 Angular 2.0.0.为什么在组件和服务上有区别?是否可以在服务中获取参数?
I'm using Angular 2.0.0. Why the difference in component and service? Is it possible to get params in a service?
https://github.com/angular/angular/issues/11023
推荐答案
我们可以将 ActivatedRoute 从组件传递给服务.然后订阅service类中的route.params
We can pass ActivatedRoute to service from component. Then subscribe to route.params in service class
这篇关于Angular 2 在服务中获取 routeParams的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文