简体   繁体   English

如何将逻辑从组件移动到服务(Angular)

[英]How to move the logic from component to service (Angular)

I have components that save data to local storage and i want to move all the logic from the component to service.我有将数据保存到本地存储的组件,我想将所有逻辑从组件移动到服务。 This is my Components: I Want to move all the stuff from ngOnInit to service.这是我的组件:我想将所有东西从 ngOnInit 转移到服务。

   import { Component, OnInit, Input } from '@angular/core';
    import { Report } from 'src/app/shared/entity/report.entity';
    import {Utils} from '../../../../shared/utils';

    @Component({
      selector: 'app-kit-header',
      templateUrl: './kit-header.component.html',
      styleUrls: ['./kit-header.component.sass']
    })
    export class KitHeaderComponent implements OnInit {
      @Input() reportData: Report;
      public dateCreate: any;
      public year: string;
      public deadLine: any;
      public typeName: string;
      public hour: any;
      public date: any;
      constructor() { }

      ngOnInit() {
        if (localStorage.getItem('dateCreate') === null) {
          localStorage.setItem('dateCreate', JSON.stringify(this.reportData.dateCreated));
          localStorage.setItem('year', JSON.stringify(this.reportData.year));
          localStorage.setItem('deadLine', JSON.stringify(this.reportData.deadLine));
          localStorage.setItem('typeName', this.reportData.name);
          this.dateCreate = localStorage.getItem('dateCreate');
          this.year = localStorage.getItem('year');
          this.deadLine = localStorage.getItem('deadLine');
          this.typeName = localStorage.getItem('typeName');
        } else {
          this.dateCreate = localStorage.getItem('dateCreate');
          this.year = localStorage.getItem('year');
          this.deadLine = localStorage.getItem('deadLine');
          this.typeName = localStorage.getItem('typeName');
        }
        this.deadLine = new Date(JSON.parse(this.deadLine));
        this.hour = new Date(JSON.parse(this.dateCreate)).toLocaleTimeString();
        this.date = new Date(JSON.parse(this.dateCreate)).toLocaleDateString();
      }


      formatedDate(deadLine: Date) {
        return Utils.parseHebrewDate(deadLine);
      }

    }

Service:服务:

saveKitData(dateCreated, year, deadLine, name) {
???
}

thanks谢谢

You need to move the whole logic to that method, instead of passing each property, you can pass the whole object reportData您需要将整个逻辑移至该方法,而不是传递每个属性,您可以传递整个 object reportData

saveKitData(reportData : any) {
if (localStorage.getItem('dateCreate') === null) {
          localStorage.setItem('dateCreate', JSON.stringify(reportData.dateCreated));
          .....
          this.dateCreate = localStorage.getItem('dateCreate');
          this.year = localStorage.getItem('year');
          this.deadLine = localStorage.getItem('deadLine');
          this.typeName = localStorage.getItem('typeName');
        } else {
          this.dateCreate = localStorage.getItem('dateCreate');
          this.year = localStorage.getItem('year');
          this.deadLine = localStorage.getItem('deadLine');
          this.typeName = localStorage.getItem('typeName');
        }
        this.deadLine = new Date(JSON.parse(this.deadLine));
        this.hour = new Date(JSON.parse(this.dateCreate)).toLocaleTimeString();
        this.date = new Date(JSON.parse(this.dateCreate)).toLocaleDateString();
}

It is better to write a service and use dependency injection to use it in your component like below: at first, encapsulate data in a class:最好编写一个服务并使用依赖注入在您的组件中使用它,如下所示:首先,将数据封装在 class 中:

export class CustomDataDto{
      public dateCreate: any;
      public year: string;
      public deadLine: any;
      public typeName: string;
      public hour: any;
      public date: any;
}

Then move your code into a Service:然后将您的代码移动到服务中:

@Injectable()
export class YourDataStorageService {
  public CustomDataDto myGetDataMethod(reportData : any){
      localStorage.setItem('dateCreate',         
                            JSON.stringify(reportData.dateCreated));
          .....
      let data=new CustomDataDto ();
      if (localStorage.getItem('dateCreate') === null) {
          localStorage.setItem('dateCreate', 
          JSON.stringify(this.reportData.dateCreated));
          localStorage.setItem('year', JSON.stringify(this.reportData.year));
          localStorage.setItem('deadLine', JSON.stringify(this.reportData.deadLine));
          localStorage.setItem('typeName', this.reportData.name);
          data.dateCreate = localStorage.getItem('dateCreate');
          data.year = localStorage.getItem('year');
          data.deadLine = localStorage.getItem('deadLine');
          data.typeName = localStorage.getItem('typeName');
        } else {
          data.dateCreate = localStorage.getItem('dateCreate');
          data.year = localStorage.getItem('year');
          data.deadLine = localStorage.getItem('deadLine');
          data.typeName = localStorage.getItem('typeName');
        }
        data.deadLine = new Date(JSON.parse(this.deadLine));
        data.hour = new Date(JSON.parse(this.dateCreate)).toLocaleTimeString();
        data.date = new Date(JSON.parse(this.dateCreate)).toLocaleDateString();
        return data;
}
}

In the Next step,you must declare it in NgModule:在下一步中,您必须在 NgModule 中声明它:

@NgModule({
  providers: [YourDataStorageService ];
})

At the end, you can use it in your component:最后,您可以在组件中使用它:

export class KitHeaderComponent implements OnInit {
    constructor( injector: Injector,
                 private _yourDataStorageServiceProxy: YourDataStorageService) {
         super(injector);      
     }
    ngOnInit() {
      let data = this._yourDataStorageServiceProxy.myGetDataMethod();
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM