在模型类Angular中注入服务

时间:2018-01-09 11:51:57

标签: angular typescript service dependency-injection

假设我有一个服务,其中包含有关Angular应用程序中已记录用户的信息。我有一个名为Sell的模型,其中包含一个字段,即实例化某个id对象的用户Sell。是否有一种方法可以注入(我不知道“注入”是否是这里最好的词)模型中的用户服务以这种方式调用构造函数时,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
  }
}

2 个答案:

答案 0 :(得分:7)

你要做的事情是合理的,你试图这样做的方式被认为是一种不好的做法(当天的大火焰战争,所以不会进入那个)

做这样的事情的更好方法之一是使用工厂来构建你的对象。

所以你的代码看起来像是:

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

这样一切都保持分离和可测试。

答案 1 :(得分:3)

你不应该在那里注射服务。出售课程也会非常“聪明”。然后。我认为有两种正确的方法可以做到:

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

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

第二种方法是创建另一个SellService,它将注入UserService。它将有方法createNewSell(),它将与上面的代码片段相同。