gpt4 book ai didi

Angular 2在服务中获取routeParams

转载 作者:太空狗 更新时间:2023-10-29 17:18:56 25 4
gpt4 key购买 nike

我想将逻辑从组件转移到服务。但是我发现我无法获取服务中的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;
}
};

当我调试时,我可以看到参数在组件中被填充而在服务中为空。这就是结果

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

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

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

最佳答案

根据 this你必须向下遍历路由树并从树底部的路由获取数据。

@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
});


});
}
}

关于Angular 2在服务中获取routeParams,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40219790/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com