1

我需要在我的服务中获取路由参数

import {Inject, Injectable} from '@angular/core';
import {BehaviorSubject} from 'rxjs';
import {ActivatedRoute, NavigationEnd, Router} from '@angular/router';

@Injectable({
  providedIn: 'any'
})
export class LocationService {

  constructor(
    private router: Router,
    private route: ActivatedRoute
  ) {
    console.log('ddd ', );

    this.router.events.subscribe((data) => {
      if (data instanceof NavigationEnd) {
        console.log('this.route.snapshot.params[\'city\']; ', this.route.firstChild.snapshot.params['city']);
      }
    });
  }
}

在组件中

this.router.events.subscribe((data) => {
  if (data instanceof NavigationEnd) {
    console.log('this.route.snapshot.params[\'city\']; ', this.route.firstChild.snapshot.params['city']);
  }
});

工作正常,但在服务city中未定义

如果我在组件中提供定位服务

@Component({
  selector: 'app-city-chooser',
  templateUrl: './city-chooser.component.html',
  styleUrls: ['./city-chooser.component.scss'],
  providers: [LocationSerivce]
})

我的服务调用了两次(我在不同的组件中使用我的服务)

如何在我的服务中获取路由参数?


UPD:项目有两个模块!!!BasicModule 和 DashboardModule

4

1 回答 1

0

您可以将参数传递给服务方法并做任何您想做的事情,在服务中获取路由参数不是我们应该避免的好方法。

export class LocationService {
 constructor() {}
 
 doSomething(param) {
  // write your logic here
  console.log(param)
 }

在组件中

constructor(private route: ActivatedRoute, private service: LocationService) {
   const params = this.route.snapshot.params['city'];
   this.service.doSomething(params)
}

希望这有效。

于 2020-08-06T10:00:53.737 回答