准备2个版本的btnRef
export abstract class BtnRef {
version: Version;
}
export class BtnV1 extends BtnRef {
version = new Version('1.0.0');
}
export class BtnV2 extends BtnRef {
version = new Version('1.0.1');
}
export const btnProvide: Provider[] = [{
provide: BtnRef,
useClass: BtnV1,
multi: true
}, {
provide: BtnRef,
useClass: BtnV1,
multi: true
}, {
provide: BtnRef,
useClass: BtnV2,
multi: true
}];
-- 获取最新版本ref
export class BtnVersion {
refArray: BtnRef[] = [];
constructor(refs: BtnRef[]) {
// 去除版本号一样的ref
this.refArray = _.sortedUniqBy(_.flattenDeep(refs), (o) => o.version.full);
}
getLatest(): BtnRef {
return _.maxBy(this.refArray, (o) => o.version.full);
}
}
export const NEWBTNREF = new InjectionToken<BtnRef>('BTNREF');
export function btnVersionFactory(btnRef: BtnRef) {
return new BtnVersion([btnRef]);
}
export const BTNREF_FACTORY: Provider[] = [
{
provide: BtnVersion,
useFactory: btnVersionFactory,
deps: [BtnRef]
},
{
provide: NEWBTNREF,
useFactory: (version: BtnVersion) => {
return version.getLatest();
},
deps: [BtnVersion]
}
];
- 组件中使用
@Component({
selector: 'app-btn',
templateUrl: './btn.component.html',
styleUrls: ['./btn.component.css']
})
export class BtnComponent implements OnInit {
constructor(
@Inject(NEWBTNREF) public btns: BtnRef
) { }
ngOnInit() {
console.log(this.btns);
}
}
- 去掉@Inject(NEWBTNREF)
export class BtnVersion {
refArray: BtnRef[] = [];
constructor(refs: BtnRef[]) {
// 去除版本号一样的ref
this.refArray = _.sortedUniqBy(_.flattenDeep(refs), (o) => o.version.full);
}
getLatest(): NewBtnRef {
return _.maxBy(this.refArray, (o) => o.version.full);
}
}
export abstract class NewBtnRef extends BtnRef { }
export function btnVersionFactory(btnRef: BtnRef) {
return new BtnVersion([btnRef]);
}
export const BTNREF_FACTORY: Provider[] = [
{
provide: BtnVersion,
useFactory: btnVersionFactory,
deps: [BtnRef]
},
{
provide: NewBtnRef,
useFactory: (version: BtnVersion) => {
return version.getLatest();
},
deps: [BtnVersion]
}
];
@Component({
selector: 'app-btn',
templateUrl: './btn.component.html',
styleUrls: ['./btn.component.css']
})
export class BtnComponent implements OnInit {
constructor(
public btns: NewBtnRef
) { }
ngOnInit() {
console.log(this.btns);
}
}
- 隔离
@Component({
selector: 'app-btn',
templateUrl: './btn.component.html',
styleUrls: ['./btn.component.css'],
providers: [
BTNREF_FACTORY
]
})
export class BtnComponent implements OnInit {
constructor(
public btns: NewBtnRef
) { }
ngOnInit() {
console.log(this.btns);
}
}