【问题标题】:Inject a service in a model class Angular在模型类 Angular 中注入服务
【发布时间】:2018-06-18 10:55:57
【问题描述】:

假设我有一个服务,其中包含有关我的 Angular 应用程序中登录用户的信息。我有一个名为Sell 的模型,其中包含一个字段,该字段是用户id,他实例化了一些Sell 对象。有没有办法在调用构造函数时以这种方式注入模型内部的用户服务(我不知道“inject”是否是这里最好的词),Sell 自动获取用户 ID并将其分配给对象?

例子:

user.service.ts

...
@Injectable()
export class UserService {
  private _id: string = 'some_id';

  get id(): string {
    return this._id;
  }    
}

sell.model.ts

export class Sell {
  userId: string;
  price: number;
  ...

  constructor() {
    // some way to have userService here
    this.userId = this.userService.id;
  }
}

some.component.ts

import { Component } from '@angular/core';
import { Sell } from '../models/sell.model';

@Component({
  ...
})
export class SomeComponent {

  newSell() {
    let sell = new Sell();
    // with this line, I'd want that the model itself assign user id
    // to its object.
    console.log(sell.userId) // some_id
  }
}

【问题讨论】:

  • 除了技术实现细节之外,您应该知道这可以被认为违反了单一责任原则(SOLID中的S)
  • 哪里没有注入到组件构造函数中
  • 谢谢@WimOmbelets,我不知道SOLID。我会寻找这个设计原则。

标签: angular typescript service dependency-injection


【解决方案1】:

你不应该在那里注入服务。那么销售类将太“聪明”了。我认为有两种正确的方法:

将 UserService 注入 SomeComponent (只需将其添加到构造函数中),然后执行

let sell = new Sell(this.userService.id);

第二种方法是创建另一个 SellService,它将注入 UserService。它会有createNewSell()方法,和上面的sn-p代码一样。

【讨论】:

  • 谢谢@mdziob。是的,Sell 类只是“聪明”并且阅读响应和 cmets,这对我的应用程序不利。我更喜欢第二种方法,使用服务来创建一个新对象。
【解决方案2】:

您尝试做的事情是合理的,您尝试做的方式被认为是一种不好的做法(当年的激烈战争,所以不打算参与其中)

执行此类操作的更好方法之一是使用工厂来构造您的对象。

所以你的代码看起来像:

// Component needing model
@Component(...)
class SomeComponent {
    constructor(sellFactory: SellFactoryService){
        const sell = sellFactory.getNewSell();
        console.log(sell.userId)

}

/// Sell factory
@Injectable()
class SellFactoryService {
    constructor(private _userService: UserService){ 
    }

    getNewSell(){
       const sell = new Sell();
       sell.userId = this._userService.id;
       return sell;
    }
}

// Your sell class remains dumb (btw Sale would be a much better name for a model)
export class Sell {
  userId: string;
  price: number;
}

这样,一切都保持解耦和可测试。

【讨论】:

  • 谢谢@masimplo。我喜欢用这种方式来解决我的问题(即使是“工厂”这个词我现在也很清楚了)。
  • 在这个例子中,如果Sell 需要一个方法,getNextUser() 或者需要调用服务中的方法的东西呢?
猜你喜欢
  • 2014-09-19
  • 2019-01-22
  • 2016-11-28
  • 1970-01-01
  • 1970-01-01
  • 2018-04-21
  • 1970-01-01
  • 2017-08-24
  • 2015-12-02
相关资源
最近更新 更多