【发布时间】: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