【问题标题】:Pass injectable service to the parent component in Angular将可注入服务传递给 Angular 中的父组件
【发布时间】:2021-11-13 02:39:09
【问题描述】:

使用 Angular 12

我想创建一个基组件类,它具有通用功能,例如从端点获取对象列表、分页等,等等,

父类

class BaseComponent<T> implements onInIt {
  itemsList: Array<T>;

  constructor(
    private itemService: any
  ) {}

  ngOnInit() {
    this.getList();
  }

  getList() {
    this.itemService.list().subscribe(res => {
      this.itemsList = res;
    });
  }
  }
}

每个子组件都扩展了 BaseComponent,其中 T 是子类所表示的对象类型的接口。

例子

// UserModel
export interface User {
  id: string;
  name: string;
}

export interface Payment {
  id: string;
  user: User;
  amount: number;
}

UserComponent 将是

export class UserComponent extends BaseComponent<User> {

  constructor(
    private userService: UserService
  ) {
    super();   <---
  }

}

我想将userService 传递给父组件中的itemService,以便它可以使用此服务中的list() 方法。

如何将可注入服务传递给父组件类?

错误

Consider using the @Inject decorator to specify an injection token
This type is not supported as injection token (any).

【问题讨论】:

  • 为什么不能在基础组件中注入 userService?
  • 只需在您的super 呼叫中传递userService,例如super(userService)
  • @RiteshWaghela 用错误更新了问题。该错误实际上与定义为any的类型有关。

标签: angular typescript


【解决方案1】:

要解决此错误,只需更改BaseComponent 的构造函数,将@Inject(String) 装饰器添加到itemService

@Inject() 类构造函数的依赖参数上的参数装饰器 指定依赖项的自定义提供程序。

@Inject() 是一种手动机制,用于让 Angular 知道 必须注入参数。

constructor(@Inject(String) private itemService: any) {}

【讨论】:

    猜你喜欢
    • 2020-11-21
    • 1970-01-01
    • 2020-01-06
    • 1970-01-01
    • 2021-09-20
    • 1970-01-01
    • 2018-08-22
    • 2018-05-20
    • 2017-08-30
    相关资源
    最近更新 更多