簡體   English   中英

Angular 基於組件@Input屬性的構造函數中的服務注入參數

[英]Angular Service inject parameter in constructor based on component @Input property

我在構造函數中有一個帶有參數的服務,這里是一個簡單的字符串,稍后在 url 或其他對象上。 該參數是為服務的內部行為設置的,這里只是實例化不同的值。


  constructor(@Inject(AUTHOR_TYPE) public authType: string ) { 

    console.log('Auth type is ' + authType);
    
    if(authType == 'international')
      this.authors = ["a1","a2","a2","a3"];
    else
      this.authors = ["local1","local2","local2","local3"];
  }

該服務在組件內部使用。 這個組件有一個輸入參數,使組件靈活和可重用。

export class AuthorsComponent implements OnInit {

  @Input('type')
  type: 'local' | 'international' = "local";
  authors: string[];
  
  constructor(service: AuthorsService) {
    this.authors = service.getAuthors();
   }

  ngOnInit(): void {

    console.log('component init as ' + this.type);
  }
}

我希望有一個組件能夠使用輸入參數(或其他綁定模式)在不同類型之間切換,並且基於組件類型能夠設置內部服務以更改行為。

在下面的實時示例中,我只有一個帶有自定義參數的組件作者,並且在服務內部檢索作者列表,有沒有辦法實現這一點?

活生生的例子


[更新]

在服務上使用 @Inject 並實際使用 2 個組件和 2 個預定義的 InjectionTocken 的可能解決方案。 似乎仍然不是最佳解決方案,因為我有一個通用組件或多或少是空的,只是摸索並顯示子組件+ 2個指定組件。 到達 scope 但我生成了太多組件。 仍然對其他解決方案持開放態度。 謝謝

可能的解決方案

您是否需要使用構造函數和自定義注入令牌?

我在這里使用 ngOnInit 以及 getter 和 setter https://stackblitz.com/edit/angular-ivy-9a7tfx?file=src/app/authors.service.ts

如果有人對一種可能的解決方案感興趣,我想出了一個很好且簡單的解決方案:

公開一個枚舉類型的輸入屬性 [mode] 的 selector.component

import { Component, OnInit, Input } from '@angular/core';

@Component({
  selector: 'app-selector',
  template: `<div > {{ mode }}</div>`,
  styleUrls: ['./selector.component.scss']
})
export class SelectorComponent implements OnInit {

  @Input('mode') mode : ModeEn = ModeEn.first;

  constructor() { }

  ngOnInit(): void {
  }

}

export enum ModeEn{
  first = 'first',
  second = 'second'
}

只需導入枚舉並為其分配新屬性即可輕松地從其他組件中使用

import { ModeEn } from './selector/selector.component';
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
  <app-selector [mode]="mode.first"></app-selector>
  <app-selector [mode]="mode.second"></app-selector>`,
  styleUrls: ['./app.component.scss']
})
export class AppComponent {

  mode = ModeEn;
}

通過這種方式,應用程序選擇器組件公開了所有可能的模式,並且在哪里使用導入將簡化並將可能的模式限制為僅可用的模式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM