Angular 9-如何将动态参数注入服务构造函数

问题描述

我需要向以下形式的后端网址发出请求:

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

其中 id1 id2 是动态数字。 我曾想过使用在构造函数中带有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 ****/}

}

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

解决方法

我不知道您在哪里获得动态ID,但实际上您可以将它们放在provider数组中,并像注入令牌一样使用依赖项注入。如果可以为课程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
  }
}

,

让服务成为无状态的服务更好,它可以降低应用程序的复杂性并为您省去一些问题和调试工作,对于您而言,这是没有必要的,因为您始终可以获取 item1Id item2Id ,因此,让激活的路由保存应用程序的状态(在这种情况下,状态就是选择的Item1Id和Item2Id),并创建可从任何地方调用的无状态服务拥有Item API的逻辑。

这就是我设想您的服务的方式(请记住,这只是一个示例,因为我不完全了解您的语义和用例)

ItemService

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 */
  }
}

然后,只要您可以访问 ActivatedRouteSnapshot ActivatedRoute

,就可以在任何地方使用此服务

在解析器中用于路线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 库之类的东西来管理您的状态),尽管如此,您确实不知道不必将参数传递给服务的构造函数,则应使其保持无状态并将参数传递给方法。