【问题标题】:Angular 9 - how to inject dynamic parameters into a service constructorAngular 9 - 如何将动态参数注入服务构造函数
【发布时间】:2020-08-11 17:09:22
【问题描述】:

我需要向以这种形式出现的后端 url 发出请求:

localhost:8000/myapp/item1/:id1/item2/:id2/item3

其中 id1id2 是动态数字。 我考虑过在构造函数中使用一个接受 2 个参数的服务,就像这样

export class Item3Service {

  private id1: number;
  private id2: number;

  constructor(
    id1: number,
    id2: number
  ) {
    this.id1 = id1;
    this.id2 = id2;
  }

  getList() {/**** implementation here ****/}
  getDetail(id3: number) {/**** implementation here ****/}
  create() {/**** implementation here ****/}
  update(id3: number) {/**** implementation here ****/}
  delete(id3: number) {/**** implementation here ****/}

}

我真的不知道如何将参数注入到构造函数中。我还需要在 resolver 中使用此服务,我如何在解析器中将参数传递给它? 在这种情况下创建注入令牌听起来毫无用处,因为令牌值每次都应该改变。我的想法已经用完了

【问题讨论】:

  • 所以你基本上是想把 id1 和 id2 的值正确地放入服务中?
  • 是的,这些值应该可以在运行时修改

标签: angular angular-services angular9 angular-dependency-injection angular-token


【解决方案1】:

你的服务最好是无状态的,它会降低你的应用程序的复杂性,让你免于一些问题和调试,在你的情况下这不是必需的,因为你总是可以得到 item1Iditem2Id 来自您激活的路由,因此让激活的路由保存您的应用程序的状态(在这种情况下,状态是 Item1Id 和 Item2Id 被选中)并创建一个无状态服务,您可以从任何地方调用包含您的 Item API 的逻辑。

这是我对您的服务的设想(请记住,这只是一个需要考虑的示例,因为我不完全了解您的语义和用例)

物品服务

export class ItemService {
  constructor(private http: HttpClient) {}

  getList(item1Id: string, item2Id: string) {
    /* Call to Get List endpoint with Item1Id and Item2Id */
  }

  getDetails(item1: string, item2: string, item3: string) {
    /* Call to Get Details endpoint with Item1Id and Item2Id and Item3Id */
  }
}

那么你可以在任何地方使用这个服务,只要你可以访问 ActivatedRouteSnapshotActivatedRoute

在解析器中用于路线 item1/:item1Id/item2/:item2Id 的示例

export class ItemResolver implements Resolve<any> {
  constructor(private itemService: ItemService) {}

  resolve(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<any> {
    return this.itemService.getList(route.params['item1Id'], route.params['item2Id']);
  }
}

在组件中使用路由 item1/:item1Id/item2/:item2Id 获取项目 3 详细信息的示例

export class HelloComponent  {

  constructor(private route: ActivatedRoute, private itemService: ItemService) {}

  getDetails(item3Id) {
    this.route.params.pipe(
      take(1),
      map(({ item1Id, item2Id }) => {
        console.log(this.itemService.getDetails(item1Id, item2Id, item3Id))
      })
    ).subscribe();
  }
}

这是一个有效的 StackBlitz 演示:https://stackblitz.com/edit/angular-ivy-h4nszy

根据您提供的信息,您应该很少使用有状态服务(除非确实有必要,即使在这种情况下,我建议使用类似 ngrx 库来管理您的状态) '不需要将参数传递给你的服务的构造函数,你应该保持它无状态并将参数传递给你的方法。

【讨论】:

  • 你是对的。我错过了重点,并试图对我的服务提出不必要的担忧。在我的项目中,我可能需要 2 个(如果不是 3 个)这种类型的服务。所以我将创建一个基础 parametrized 服务类,它可以为其每个方法采用可变数量的参数,并且它将能够构建正确的 url 来查询后端
【解决方案2】:

我不知道您从哪里获得动态 ID,但实际上您可以将它们放在提供程序数组中并像使用注入令牌一样使用依赖注入。如果可以为id当然创建工厂方法

服务

export class Item3Service {

  constructor(
    @inject(LOCALE_ID) private locale: string) {}

}

app.moudle.ts

@NgModule({
  providers: [
    { provide: LOCALE_ID, useFactory: () => window.navigator.language}
  ]
})

编辑

由于 id 是您路线的一部分,我会这样做

组件

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { MyServiceService } from '../my-service.service';

@Component({
  selector: 'app-routed',
  templateUrl: './routed.component.html',
  styleUrls: ['./routed.component.scss']
})
export class RoutedComponent implements OnInit {

  constructor(private route: Router, private myService: MyServiceService) { }

  ngOnInit(): void {
    this.myService.setUrl(this.route.url)
  }

}

服务

import { Injectable } from '@angular/core';
import { ReplaySubject, Observable } from 'rxjs';
import { share, switchMap } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class MyServiceService {
  private _url$: ReplaySubject<string> = new ReplaySubject<string>(1);

  private _mydata$: Observable<string>;
  get myData$() { return this._mydata$.pipe(share()); }


  constructor() {
    this._mydata$ = this._url$.pipe(
      switchMap(url => {
        const parsedUrl = this.parseUrl(url);
        return this.callBackend(parsedUrl)
      })
    )
  }

  setUrl(url: string) {
    this._url$.next(url);
  }

  private callBackend(parsedUrl): Observable<string> {
    // call backend 
  }

  private parseUrl(url: string): number[] {
    // parse ids
  }
}

【讨论】:

  • 我不知道你从哪里得到动态 ids --> 这就是问题所在,因为这些 ids 应该在运行时改变。它们代表后端数据库中某些模型的主键。它们将是被查询的 url 的一部分。我真的不知道该怎么对付他们。也许唯一可能的解决方案是重构并将它们作为参数传递给每个服务方法。但这听起来很麻烦
  • 我不太明白,ID 保存/生成在哪里?
  • 其实我从 url 解析 ids。例如,用户在页面 /item1/1/item2/1 中。他想创建一个属于 item2 的 item3。该服务将通过在其构造函数中传递的 id1=1 和 id2=1 创建。然后服务会发送一个POST请求到后端url /item1/1/item2/1/item3/
  • 我明白了。然后你应该从路由器获取它们,然后在服务中创建一个方法来设置它们
  • 在这种情况下是的,服务最好是无状态的。但作为一般性陈述,这是非常错误的。作为状态管理的服务有许多有效的用例
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-10-04
  • 2021-09-24
  • 2022-01-02
  • 1970-01-01
  • 2020-06-03
  • 2018-03-27
  • 2014-03-29
相关资源
最近更新 更多