Having trouble exporting from an Angular2 module

£可爱£侵袭症+ 提交于 2019-12-06 08:20:19

For services use providers: [...], they will be added to the root injector (from non-lazy-loaded modules).

exports: [] is for directives, components, and pipes and modules that export directives, components, and pipes.

There are couple of mistakes I can see from here,

1) If you want to use AddService everywhere, better to inject it in AppModule as shown below, (remove AddService from arithmetic.module)

 import {AddService} from './add/arithmetic.module';

 @NgModule({
    imports:        [BrowserModule],
    declarations:   [AppComponent, AddService],
    bootstrap:      [AppComponent],
    providers:      [AddService]          //<<<===here 
})
export class AppModule { }

2) service should be injectable

import {Injectable} from '@angular/core'; //<<<===here

@Injectable()                             //<<<===here
   export class AddService {
    addTwoNumbers(a: number, b: number) : number {
        return a + b;
    } 
   }

3) How to use in app.component.ts

import {AddService} from './add/arithmetic.module';
import { Component } from '@angular/core';    

@Component({
    selector: 'my-app',
    templateUrl: 'app/app.component.html'
})
export class AppComponent {
    constructor(private s:AddService){}   //<<<===here
    calculate() {

       // var c = new AddService();

        var x = s.addTwoNumbers(3, 5);     //<<<===here
        console.log(x);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!