angular組件版本管理器

準備2個版本的btnRefcss

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
}];
複製代碼

-- 獲取最新版本refhtml

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

複製代碼
相關文章
相關標籤/搜索