简体   繁体   中英

Angular 2 - how to add a custom class?

I try to add a regular class to my project but I get

zone.js:917 Uncaught Error: Unexpected value 'Tools' declared by the module 'AppModule'. 
Please add a @Pipe/@Directive/@Component annotation.

it's just a regular typescript class that I want to be able to use verywhere in my project

it is not a directive, nor pipe, nor a component

export class Tools
{
    pascalCase(text:string)
    {
        return text.charAt(0).toUpperCase() + text.slice(1);
    }
}

here is the app module

import { NgModule, ApplicationRef } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpModule } from '@angular/http';
import { FormsModule } from '@angular/forms';
import { LocationStrategy, HashLocationStrategy } from '@angular/common';
import { CookieService } from 'angular2-cookie/core';

...    

import { Tools } from './tools.class';

@NgModule({
    imports: [
        BrowserModule,
        HttpModule,
        FormsModule,
        routing,
        CustomErrorHandlerModule
    ],
    declarations: [
        AppComponent,
        ...
        Tools
    ],

thanks

Remove Tools from declarations . There is no reason to add it if it's not a component, directive, or pipe.

There is no need to add Tools into App Module,

declarations: is used to declare components, directives, pipes that belongs to the current module. Everything inside declarations knows each other.

so just remove Tools from declaration.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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