angular组件版本管理器

作者: 杨明明abc | 来源:发表于2018-06-07 12:29 被阅读11次

准备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);
  }
}

相关文章

网友评论

    本文标题:angular组件版本管理器

    本文链接:https://www.haomeiwen.com/subject/fwfgsftx.html