typescript SpriteAnimation

SpriteAnimation
type Option = {
  canvas: HTMLCanvasElement
  src: string
  width: number
  height: number
  frameNumber: number
  fps: number
  autoPlay: boolean
}

export default class SpriteAnimation {
  private _$canvas: HTMLCanvasElement | null
  private _sprite: HTMLImageElement | {} | null
  private opts: Option
  private readonly _spriteYPerFrame: number
  private readonly _src: string
  private readonly _spriteX: number
  private readonly _spriteY: number
  private readonly _num: number
  private readonly _fps: number
  private readonly _autoplay: boolean
  private _context: CanvasRenderingContext2D

  constructor(opts: Option) {
    this.opts = opts
    this._$canvas = opts.canvas
    this._src = opts.src
    this._spriteX = opts.width
    this._spriteY = opts.height
    this._num = opts.frameNumber
    this._fps = opts.fps
    this._autoplay = opts.autoPlay

    this._sprite = null
    this._spriteYPerFrame = this._spriteY / this._num

    this._$canvas.width = this._spriteX
    this._$canvas.height = this._spriteYPerFrame
    this._context = this._$canvas.getContext('2d')
  }

  async init() {
    await this.prepare()
  }

  async prepare() {
    this._sprite = await this._loadImage(this._src)
    if (this._autoplay) {
      this.play()
    }
  }

  _loadImage(src: string) {
    return new Promise(resolve => {
      const image = new Image()
      image.onload = () => {
        resolve(image)
      }
      image.src = src
    })
  }

  _drawSprite(index: number) {
    this._context.clearRect(0, 0, this._spriteX, this._spriteY)
    if (!(this._sprite instanceof Image)) return
    this._context.drawImage(
      this._sprite,
      0,
      this._spriteYPerFrame * index,
      this._spriteX,
      this._spriteYPerFrame,
      0,
      0,
      this._spriteX,
      this._spriteYPerFrame
    )
  }

  play(repeat = false) {
    const startTime = performance.now()

    let prevFrame = 0
    let id = 0
    const loop = () => {
      const lastTime = performance.now()
      const frame = Math.floor(
        ((lastTime - startTime) / (1000 / this._fps)) % this._num
      )
      if (prevFrame > frame && !repeat) {
        window.cancelAnimationFrame(id)
        this._drawSprite(this._num - 1)
        return
      } else {
        id = window.requestAnimationFrame(loop)
      }
      this._drawSprite(frame)
      prevFrame = frame
    }
    loop()
  }
}

typescript 连接功能组件

component.ts
import * as React from 'react';
import { useDispatch, useSelector } from 'react-redux';

type Props = {
  
};

const NamedComponent: React.FunctionComponent<Props> = (props: Props) => {
  const dispatch = useDispatch();
  return null;
};

export default React.memo(NamedComponent);

typescript devex-角其余-定制数据源

datasource
import { Component, OnInit, ViewChild } from '@angular/core';
import { GeneralService } from '@sg/experts-gateway/app/core/services/general.service';
import { DxDataGridComponent } from 'devextreme-angular';
import DevExpress from 'devextreme/bundles/dx.all';
import CustomStore from 'devextreme/data/custom_store';
import DataSource from 'devextreme/data/data_source';
import { throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';

@Component({
    selector: 'sg-list',
    templateUrl: './list.component.html',
})
export class ListComponent implements OnInit {
    dataSource: any;
    @ViewChild(DxDataGridComponent, { static: true }) grid: DxDataGridComponent;

    constructor(private readonly generalService: GeneralService) {
        this.editPermissionClick = this.editPermissionClick.bind(this);
    }

    ngOnInit(): void {
        this.initGrid();
        this.initDataSource();
    }

    editPermissionClick(): void {}

    private initGrid(): void {
        this.grid.remoteOperations = true;
        this.grid.allowColumnResizing = true;
        this.grid.paging = { enabled: true, pageSize: 10 };
    }
    private initDataSource(): void {
        this.dataSource = new DataSource(
            new CustomStore({
                key: 'guid',
                load: async (loadOptions: DevExpress.data.LoadOptions): Promise<any> => this.getData(loadOptions),
            })
        );
    }

    private async getData(loadOptions: DevExpress.data.LoadOptions): Promise<any> {
        return this.generalService
            .getUsersByDevexLoadOption(loadOptions)
            .pipe(
                catchError(err => {
                    return throwError(err);
                })
            )
            .toPromise();
    }
}

typescript rxjs订阅

具有3x回调的基本rxjs订阅模板。

sub.ts
this.serverErrors.subscribe(
			( data ) => { console.log( data) }
			( error ) => { console.log( error ) }
			() => { console.log('complete') }
		)

typescript importi

import.ts
import { } from ''

typescript STI

导入样式组件主题

styles.ts
import styled, { IStyledProps } from 'theme'

typescript 格式化date.toLocalString()

ts
   const date = this.ishurHazmanatSheelonimData.taarihIshur;
        this.formattedDate = date.toLocaleDateString('en-GB', {
            day: 'numeric', month: 'numeric', year: 'numeric'
        }).replace(/ /g, '/');

typescript AngGenGuard

Tienes que estar cituado en el directorio donde manejaras el guard <br/> src / app / _guard <br/> <br/> En este guard se esta usando Alertify

bash
ng g guard auth --spec=false

#Esto generara un archivo auth.guard.ts
auth.guard.ts
//Ubicado en src/app/_guard

import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { AuthService } from '../_services/auth.service';
import { AlertifyService } from '../_services/alertify.service';


@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {
  constructor(private authService: AuthService, private router: Router,
    private alertify: AlertifyService) {}

  canActivate(): boolean {
    if (this.authService.loggedIn()) {
      return true;
    }

    this.alertify.error('you shall not pass!!!');
    this.router.navigate(['/home']);
    return false;
  }
}
routes.ts
import {Routes} from '@angular/router';
import { HomeComponent } from './home/home.component';
import { MemberListComponent } from './member-list/member-list.component';
import { AuthGuard } from './_guards/auth.guard';

export const appRoutes: Routes = [
    { path: 'home',          component: HomeComponent},
    { path: 'members',       component: MemberListComponent, canActivate: [AuthGuard]}, //Esta es la forma de proteget una unica ruta que el usuario este autentificado
    { path: '**',            redirectTo: 'home', pathMatch: 'full'}
    // Protegiendo Multiples rutas
    {
      path: '',
      runGuardsAndResolvers: 'always',
      canActivate: [AuthGuard],
      childer: [
        { path: '[MiPath]', component: [MiCOmponente]Component },
        { path: '[MiPath]', component: [MiCOmponente]Component },
        { path: '[MiPath]', component: [MiCOmponente]Component },
        ]
    }


];

typescript 延迟加载图像指令

本文的目标是在进入视口后为延迟加载图像创建一个指令。

ts
@Directive({
  selector: 'img[appLazyLoad]'
})
export class LazyLoadDirective implements AfterViewInit {
  // ...
  constructor(private el: ElementRef) {}

  private lazyLoadImage() {
    const obs = new IntersectionObserver(entries => {
      entries.forEach(({ isIntersecting }) => {
        if (isIntersecting) {
          this.loadImage();
          obs.unobserve(this.el.nativeElement);
        }
      });
    });
    obs.observe(this.el.nativeElement);
  }

  private loadImage() {
    this.srcAttr = this.src;
  }
}

typescript 按日期排序pape Angular

ts
import {Pipe, PipeTransform} from '@angular/core';
import {ISugTzerufListItems} from '../../general/Models/interfaces';

@Pipe({
    name: 'orderByDate'
})
export class OrderByDatePipe implements PipeTransform {

    transform(herkevTzerufim: ISugTzerufListItems[], args?: any): any {
        // console.log('herkevTzerufim', herkevTzerufim);
        let newTzerufim = herkevTzerufim.sort((a: any, b: any) => {
            return new Date(b.updateDate).getTime() - new Date(a.updateDate).getTime();

        })
        return newTzerufim;
    }

}