typescript 将类导入到 angular2 中的另一个类组件中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39890330/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:54:27  来源:igfitidea点击:

Import Class into another Class Component in angular2

angulartypescript

提问by

I have repeated code in my project.

我的项目中有重复的代码。

I separate it from other component to make it much easier and dynamic when changing some value. Unluckily, It doesn't work with me.

我将它与其他组件分开,以便在更改某些值时更容易和动态。不幸的是,它对我不起作用。

Here's what I have

这是我所拥有的

Repeated Code: form.ts

Repeated Code: form.ts

export class Form {
    constructor(){
        var today = new Date(),
            dd = today.getDate(),
            mm = today.getMonth() + 1,
            yyyy = today.getFullYear();

        if(dd < 10) dd = `0${dd}`;
        if(mm < 10) mm = `0${mm}`;

        today = `${yyyy}-${mm}-${dd}`;

        this.balance.dateTo = today;
    }

    public balance = {
        viewBy: 'Ad1',
        companyUnit: 'DEPED',
        financialYear: '2016',
        clients: 'Dummy Text 1'
    };
}

In other component such as balance, settlement, etc...

在其他组件中,例如余额、结算等...

I imported it on the top.

我在顶部导入它。

Here's what I have tried:

这是我尝试过的:

import { Form } from '../form';   // path is correct

export class BalanceComponent {
    form: Form;                   // I am not sure of it
                                  // this is the place I want to import repeated class
    search_data(balance){
        console.log(balance);
    }
}

systemjs.config.js

systemjs.config.js

(function (global) {
  System.config({
    paths: {
      // paths serve as alias
      'npm:': 'node_modules/'
    },
    // map tells the System loader where to look for things
    map: {
      // our app is within the app folder
      app: 'app',
      // angular bundles
      '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
      '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
      '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
      '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
      '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
      '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
      '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
      '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
      'ng2-pagination': 'npm:/ng2-pagination',
      // other libraries
      'rxjs':                      'npm:rxjs',
      'angular-in-memory-web-api': 'npm:angular-in-memory-web-api',
    },

    // packages tells the System loader how to load when no filename and/or no extension
    packages: {
      app: {
        main: './main.js',
        defaultExtension: 'js'
      },
      rxjs: {
        defaultExtension: 'js'
      },
      'angular-in-memory-web-api': {
        main: './index.js',
        defaultExtension: 'js'
      },
      'ng2-pagination': {
        main: 'index.js', defaultExtension: 'js' 
      } 
    }
  });
})(this);

回答by vardius

Now you need to initialzie your form object.

现在你需要初始化你的表单对象。

export class BalanceComponent {
    form: Form;

    constructor() {
        this.form = new Form();
    }
}

If you want to share this value between components, best idea is to create service and then inject it into components.

如果你想在组件之间共享这个值,最好的办法是创建服务,然后将它注入到组件中。

export class BalanceComponent {    
    constructor(private formService:FormService) {}
}

If you say private formService:FormServiceinside contructor. You will be able later to access this variable like this.formService.

如果你说private formService:FormService内部构造函数。稍后您将能够像this.formService.

@Injectable()
export class FormService {
    constructor(){
        var today = new Date(),
            dd = today.getDate(),
            mm = today.getMonth() + 1,
            yyyy = today.getFullYear();

        if(dd < 10) dd = `0${dd}`;
        if(mm < 10) mm = `0${mm}`;

        today = `${yyyy}-${mm}-${dd}`;

        this.balance.dateTo = today;
    }

    public balance = {
        viewBy: 'Ad1',
        companyUnit: 'DEPED',
        financialYear: '2016',
        clients: 'Dummy Text 1'
    };
}

Keep in mind that if your service is in shared module, you may get multiple instances of it. Best idea then is to configure module with Module.forRoot.

请记住,如果您的服务在共享模块中,您可能会获得它的多个实例。最好的想法是使用Module.forRoot.

By convention, the forRoot static method both provides and configures services at the same time. It takes a service configuration object and returns a ModuleWithProviders.

按照惯例,forRoot 静态方法同时提供和配置服务。它接受一个服务配置对象并返回一个 ModuleWithProviders。

Here is full Docabout it.

这是关于它的完整文档

Call forRoot only in the root application module, AppModule. Calling it in any other module, particularly in a lazy loaded module, is contrary to the intent and is likely to produce a runtime error.

Remember to import the result; don't add it to any other @NgModule list.

仅在根应用模块 AppModule 中调用 forRoot。在任何其他模块中调用它,特别是在延迟加载的模块中,与意图相反,并且可能会产生运行时错误。

记得导入结果;不要将它添加到任何其他 @NgModule 列表中。

@NgModule({
    imports: [CommonModule],
    declarations: [BalanceComponent],
    exports: [BalanceComponent]
})
export class SharedModule {
    static forRoot(): ModuleWithProviders {
        return {
            ngModule: SharedModule,
            providers: [FormService]
        };
    }
}

Then import module looks like:

然后导入模块看起来像:

@NgModule({
  imports: [
    /** other modules import **/
    SharedModule.forRoot(), // you can also pass some config here if needed
    routing
  ],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }