1
votes

All:

Im pretty new to Angular2, when I try to build a simple counter service like:

import { Injectable } from "@angular/core";

@Injectable()
export class Counter {
    count = 0;
    constructor(start = 0){
        this.count = start;
        // this.reset();
    }
    reset(start=0){
        this.count = start;
    }
    inc(){
        this.count++;
    }
    dec(){
        this.count--;
    }
    show(){
        return this.count;
    }
}

What I tried to do in constructor is set a default init parameter start to default the count to 0, but I get the error like:

(SystemJS) Can't resolve all parameters for Counter: (?).

My question is:

Is this because Angular2 will consider everything in constructor param list as dependency injection, no other type of param allowed set there or there is other reason for this error? And I have to use that reset() to achieve same purpose?

Is this correct?

Thanks

1

1 Answers

2
votes

"Is this because Angular2 will consider everything in constructor param list as dependency injection"

Yes.

What you can do though to make this work, is to use @Optional. But this would be pointless, alone. When you would you ever provide the value anyway? So it would always be 0. Pointless.

If you want to provide arbitrary values for injection, you can use @Inject and configure the value using a token. For example

import { OpaqueToken, NgModule } from '@angular/core';

export const START = new OpaqueToken("some.token");

@NgModule({
  providers: [
    { provide: START, useValue: 100 }
  ]
})
export class AppModule {}

Now you can inject it and make it optional

import { Inject, Optional } from '@angular/core';
import { START } from './app.module';

constructor(@Optional @Inject(START) start = 0) {}