使用 ngOnInit 的可重用组件

Reusable component using ngOnInit

我正在尝试制作一个可重用的组件,但我找不到让 ngOnInit 获取数据取决于组件输入的方法。

服务:

export class BookService {
  private apiUrl = 'http://localhost:5000/';
  constructor(private http: HttpClient) {}
  getBooks(): Observable<DragItem[]> {
    return this.http.get<DragItem[]>(this.apiUrl + 'books');
  }
  getNames(): Observable<DragItem[]> {
    return this.http.get<DragItem[]>(this.apiUrl + 'names');
  }
}

组件:

  ngOnInit(): void {
    this.booksService
      .getBooks() // => how can I make this dynamic depends on component props so I can pick (getBooks / getNames)
      .subscribe((response) => (this.items = response));
  }

你可以在组件中使用@Input/Suscriber/localstorage来获取要调用动态方法的方法。我假设你已经有了动态方法的名字,你可以这样称呼它:

public methodName: string = "Assign your method name dynamically to it"
ngOnInit(): void {
    this.booksService[`${methodName}`]() 
      .subscribe((response) => (this.items = response));
  }

您可以使用 Angular 的依赖提供程序来实现您的目标。 查看详情:https://angular.io/guide/dependency-injection-providers#specifying-an-alternative-class-provider

首先我们需要基础服务:

export abstract class DataItemsService {
    abstract fetch(): Observable<DataItem[]>;
}

需要将此服务注入到您的可重用组件中:

export class FeatureComponent implements OnInit {

    dataItems$: Observable<DataItem[]>;

    constructor(private readonly dataItemsService: DataItemsService) {}

    ngOnInit(): void {
        this.dataItems$ = this.dataItemsService.fetch();
    }
}

然后实施您需要的任何服务:

@Injectable({
    providedIn: 'root'
})
export class BookService implements DataItemsService {
    fetch(): Observable<DataItem[]> {
        return of([{value: 'book1'}, {value: 'book2'}]);
    }
}

@Injectable({
    providedIn: 'root'
})
export class NamesService implements DataItemsService {
    fetch(): Observable<DataItem[]> {
        return of([{value: 'name1'}, {value: 'name2'}]);
    }
}

只剩下在父组件的providers列表中指定需要的服务了

使用图书服务:

@Component({
    selector: 'app-demo1',
    template: `
        <app-feature></app-feature>
    `,
    providers: [
        { provide: DataItemsService, useClass: BookService },
    ],
})
export class Demo1Component {}

使用名称服务:

@Component({
    selector: 'app-demo1',
    template: `
        <app-feature></app-feature>
    `,
    providers: [
        { provide: DataItemsService, useClass: NamesService },
    ],
})
export class Demo1Component {}

通过将服务更改为一种方法解决

服务:

export class BookService {
  private apiUrl = 'http://localhost:5000/';
  constructor(private http: HttpClient) {}

  getData(str: string): Observable<DragItem[]> {
    return this.http.get<DragItem[]>(this.apiUrl + str);
  }
}

组件:

  @Input() type: string = '';
  @Input() methodName = '';
  items: DragItem[] = [];
  selectedItems: DragItem[] = [];
  searchInput = new FormControl('');
  page: number = 1;
  pageSize: number = 10;

  constructor(private booksService: BookService) {}

  ngOnInit(): void {
    this.booksService
      .getData(this.methodName)
      .subscribe((response: DragItem[]) => (this.items = response));
  }