Ped*_*tes 1 service dependency-injection typescript angular
假设我有一个服务,其中包含有关Angular应用程序中已记录用户的信息.我有一个名为的模型Sell
,它包含一个id
实例化某个Sell
对象的用户的字段.有没有办法注入(我不知道" 注入 "是否是这里最好的词)模型中的用户服务以这种方式调用构造函数时,Sell会自动获取用户ID并将其分配给对象?
例:
user.service.ts
...
@Injectable()
export class UserService {
private _id: string = 'some_id';
get id(): string {
return this._id;
}
}
Run Code Online (Sandbox Code Playgroud)
sell.model.ts
export class Sell {
userId: string;
price: number;
...
constructor() {
// some way to have userService here
this.userId = this.userService.id;
}
}
Run Code Online (Sandbox Code Playgroud)
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
}
}
Run Code Online (Sandbox Code Playgroud)
你想要做的是合理的,你试图这样做的方式被认为是一种不好的做法(当天的大火焰战争,所以不会进入那个)
做类似事情的更好方法之一是使用工厂来构建对象.
所以你的代码看起来像:
// 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;
}
Run Code Online (Sandbox Code Playgroud)
这样一切都保持分离和可测试.