How do I do dependency injection with service in Angular 5?









up vote
-2
down vote

favorite












How do I do dependency injection with service?



I got the typescript notification:




[Angular] Can't resolve all parameters for LandingComponent in
landing.component.ts:
([object Object], ?).





Update



I shouldn't do just use LangService in constructor like this:




private _langService: LangService;




Because LangService is a implementation. In real case there will be few implementations like LangMockedSerives, langService_01, langService_02. Thereby landing component should know nothig about implementation and work with interfaces only.




Service and it's interface



export interface ILangService 


export class LangService implements ILangService



Component



import ILangService from '../../services/Ilang.service';

@Component(
selector: 'app-landing',
templateUrl: './landing.component.html',
styleUrls: ['./landing.component.less']
)

export class LandingComponent
private langService: ILangService
constructor(
private http: HttpClient,
_langService: ILangService;
)
this._langService = langService;




app.module.ts



import ILangService from './services/Ilang.service';
import LangService from './services/Lang.service';

@NgModule(
declarations: [
AppComponent,
LandingComponent,
],
imports: [
BrowserModule,
HttpClientModule,
RouterModule.forRoot([
path: '', component: LandingComponent ,
], useHash: false ),
],
providers: [
LangService
],
bootstrap: [AppComponent]
)
export class AppModule









share|improve this question























  • In your landing component, you just have to do private _langService: langService; that's it and remove all those extra stuff
    – Suryan
    Nov 12 at 1:05










  • @Suryan LangService is a implementation. In real case there will be few implementations like LangMockedSerives, langService_01, langService_02. Thereby landing component should know nothig about implementation and work with interfaces only.
    – mr_blond
    Nov 12 at 1:21















up vote
-2
down vote

favorite












How do I do dependency injection with service?



I got the typescript notification:




[Angular] Can't resolve all parameters for LandingComponent in
landing.component.ts:
([object Object], ?).





Update



I shouldn't do just use LangService in constructor like this:




private _langService: LangService;




Because LangService is a implementation. In real case there will be few implementations like LangMockedSerives, langService_01, langService_02. Thereby landing component should know nothig about implementation and work with interfaces only.




Service and it's interface



export interface ILangService 


export class LangService implements ILangService



Component



import ILangService from '../../services/Ilang.service';

@Component(
selector: 'app-landing',
templateUrl: './landing.component.html',
styleUrls: ['./landing.component.less']
)

export class LandingComponent
private langService: ILangService
constructor(
private http: HttpClient,
_langService: ILangService;
)
this._langService = langService;




app.module.ts



import ILangService from './services/Ilang.service';
import LangService from './services/Lang.service';

@NgModule(
declarations: [
AppComponent,
LandingComponent,
],
imports: [
BrowserModule,
HttpClientModule,
RouterModule.forRoot([
path: '', component: LandingComponent ,
], useHash: false ),
],
providers: [
LangService
],
bootstrap: [AppComponent]
)
export class AppModule









share|improve this question























  • In your landing component, you just have to do private _langService: langService; that's it and remove all those extra stuff
    – Suryan
    Nov 12 at 1:05










  • @Suryan LangService is a implementation. In real case there will be few implementations like LangMockedSerives, langService_01, langService_02. Thereby landing component should know nothig about implementation and work with interfaces only.
    – mr_blond
    Nov 12 at 1:21













up vote
-2
down vote

favorite









up vote
-2
down vote

favorite











How do I do dependency injection with service?



I got the typescript notification:




[Angular] Can't resolve all parameters for LandingComponent in
landing.component.ts:
([object Object], ?).





Update



I shouldn't do just use LangService in constructor like this:




private _langService: LangService;




Because LangService is a implementation. In real case there will be few implementations like LangMockedSerives, langService_01, langService_02. Thereby landing component should know nothig about implementation and work with interfaces only.




Service and it's interface



export interface ILangService 


export class LangService implements ILangService



Component



import ILangService from '../../services/Ilang.service';

@Component(
selector: 'app-landing',
templateUrl: './landing.component.html',
styleUrls: ['./landing.component.less']
)

export class LandingComponent
private langService: ILangService
constructor(
private http: HttpClient,
_langService: ILangService;
)
this._langService = langService;




app.module.ts



import ILangService from './services/Ilang.service';
import LangService from './services/Lang.service';

@NgModule(
declarations: [
AppComponent,
LandingComponent,
],
imports: [
BrowserModule,
HttpClientModule,
RouterModule.forRoot([
path: '', component: LandingComponent ,
], useHash: false ),
],
providers: [
LangService
],
bootstrap: [AppComponent]
)
export class AppModule









share|improve this question















How do I do dependency injection with service?



I got the typescript notification:




[Angular] Can't resolve all parameters for LandingComponent in
landing.component.ts:
([object Object], ?).





Update



I shouldn't do just use LangService in constructor like this:




private _langService: LangService;




Because LangService is a implementation. In real case there will be few implementations like LangMockedSerives, langService_01, langService_02. Thereby landing component should know nothig about implementation and work with interfaces only.




Service and it's interface



export interface ILangService 


export class LangService implements ILangService



Component



import ILangService from '../../services/Ilang.service';

@Component(
selector: 'app-landing',
templateUrl: './landing.component.html',
styleUrls: ['./landing.component.less']
)

export class LandingComponent
private langService: ILangService
constructor(
private http: HttpClient,
_langService: ILangService;
)
this._langService = langService;




app.module.ts



import ILangService from './services/Ilang.service';
import LangService from './services/Lang.service';

@NgModule(
declarations: [
AppComponent,
LandingComponent,
],
imports: [
BrowserModule,
HttpClientModule,
RouterModule.forRoot([
path: '', component: LandingComponent ,
], useHash: false ),
],
providers: [
LangService
],
bootstrap: [AppComponent]
)
export class AppModule






angular service dependency-injection






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 14 at 8:47









j3ff

1,82311125




1,82311125










asked Nov 12 at 0:50









mr_blond

15411




15411











  • In your landing component, you just have to do private _langService: langService; that's it and remove all those extra stuff
    – Suryan
    Nov 12 at 1:05










  • @Suryan LangService is a implementation. In real case there will be few implementations like LangMockedSerives, langService_01, langService_02. Thereby landing component should know nothig about implementation and work with interfaces only.
    – mr_blond
    Nov 12 at 1:21

















  • In your landing component, you just have to do private _langService: langService; that's it and remove all those extra stuff
    – Suryan
    Nov 12 at 1:05










  • @Suryan LangService is a implementation. In real case there will be few implementations like LangMockedSerives, langService_01, langService_02. Thereby landing component should know nothig about implementation and work with interfaces only.
    – mr_blond
    Nov 12 at 1:21
















In your landing component, you just have to do private _langService: langService; that's it and remove all those extra stuff
– Suryan
Nov 12 at 1:05




In your landing component, you just have to do private _langService: langService; that's it and remove all those extra stuff
– Suryan
Nov 12 at 1:05












@Suryan LangService is a implementation. In real case there will be few implementations like LangMockedSerives, langService_01, langService_02. Thereby landing component should know nothig about implementation and work with interfaces only.
– mr_blond
Nov 12 at 1:21





@Suryan LangService is a implementation. In real case there will be few implementations like LangMockedSerives, langService_01, langService_02. Thereby landing component should know nothig about implementation and work with interfaces only.
– mr_blond
Nov 12 at 1:21













3 Answers
3






active

oldest

votes

















up vote
0
down vote



accepted










Updated Answer



If you want to use different implementations for the same service you should create an InjectionToken<T> and provide the right implementation for your interface in your module declarations.



Interface - lang.service.ts



Create an injection token that will be recognized by the injector typed with ILangService interface



export const LangService = new InjectionToken<ILangService>('LangService');

export interface ILangService


1st module - english.module.ts



Provide EnglishLangService for the LangService injection token where EnglishLangService implements ILangService interface



import LangService from './services/lang.service';
import EnglishLangService from './services/english-lang.service';

@NgModule(
declarations: [ LandingComponent ],
providers: [
provide: LangService, useClass: EnglishLangService
]
)
export class EnglishModule


2nd module - french.module.ts



Provide FrenchLangService for the LangService injection token where FrenchLangService implements ILangService interface



import LangService from './services/lang.service';
import FrenchLangService from './services/french-lang.service';

@NgModule(
declarations: [ LandingComponent ],
providers: [
provide: LangService, useClass: FrenchLangService
]
)
export class FrenchModule


Component - landing.component.ts



This way you can inject LangService in your component and the injector will retrieve the implementation provided in your module



import LangService from '../../services/lang.service';

@Component(
selector: 'app-landing',
templateUrl: './landing.component.html',
styleUrls: ['./landing.component.less']
)
export class LandingComponent
constructor(
private http: HttpClient,
private langService: LangService,
)



Testing - mock-lang.service.ts



When testing you will be able to provide your mock implementation the same way you provide the right implementation in your application modules



import LangService from './services/lang.service';
import MockLangService from './services/mock-lang.service';

TestBed.configureTestingModule(
providers: [
provide: LangService, useClass: MockLangService ,
],
);


Original Answer



You should import your service with the class instead of the interface



import LangService from '../../services/lang.service';

@Component(
selector: 'app-landing',
templateUrl: './landing.component.html',
styleUrls: ['./landing.component.less']
)
export class LandingComponent
constructor(
private http: HttpClient,
private langService: LangService;
)



Also don't forget to set the @Injectable() decorator on your service class declaration



import Injectable from '@angular/core';

@Injectable()
export class LangService implements ILangService


And of course, you have to provide the service to your module



import LangService from './services/Lang.service';

@NgModule(
declarations: [
AppComponent,
LandingComponent,
],
imports: [ ... ],
providers: [
LangService
],
bootstrap: [AppComponent]
)
export class AppModule


You can read about Angular Dependency Injection here: https://angular.io/guide/dependency-injection



Another interesting link for advance service declarations: https://offering.solutions/blog/articles/2018/08/17/using-useclass-usefactory-usevalue-useexisting-with-treeshakable-providers-in-angular/






share|improve this answer






















  • LangService is a implementation. In real case there will be few implementations like LangMockedSerives, langService_01, langService_02. Thereby landing component should know nothig about implementation and work with interfaces only.
    – mr_blond
    Nov 12 at 10:40










  • I updated the answer
    – j3ff
    Nov 12 at 15:43

















up vote
0
down vote













service.ts



import Injectable from '@angular/core';
import HttpClient, Response, RequestOptions, Headers from '@angular/common/http';
import Observable from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';

export interface ILangService


@Injectable()
export class LangService implements ILangService

constructor(private http: HttpClient) <-- httpclient for angular6


getData(): Observable<any>
return this.http.get('https://..../');
.map(this.extractData)
.catch(this.handleError);


private extractData(res: Response) ;


private handleError(error: any)
const errMsg = (error.message) ? error.message :
error.status ? `$error.status - $error.statusText` : 'Server error';
console.error(errMsg);
console.log('Error....!');
return Observable.throw(errMsg);




Component:-



import LangService from '../../services/lang.service'; <-- Import sevice here

@Component(
selector: 'app-landing',
templateUrl: './landing.component.html',
styleUrls: ['./landing.component.less']
)

export class LandingComponent
constructor(
private http: HttpClient,
_langService: LangService <--- service
)

ngOnInit()
let thisx = this;
this._langService.getData().subscribe(
function (success)
// alert here on success
alert (success);
,
error => console.log('Getting Server Data Error :: ' +
JSON.stringify(error)));







share|improve this answer






















  • LangService is a implementation. In real case there will be few implementations like LangMockedSerives, langService_01, langService_02. Thereby landing component should know nothig about implementation and work with interfaces only.
    – mr_blond
    Nov 12 at 10:40

















up vote
0
down vote













LangService shoul be removed from app.module.ts providers:



@NgModule(
declarations: [
AppComponent,
LandingComponent,
],
imports: [
BrowserModule,
HttpClientModule,
RouterModule.forRoot([
path: '', component: LandingComponent ,
], useHash: false ),
],
providers: ,
bootstrap: [AppComponent]
)
export class AppModule


And interface should be added to providers in component:



import LangService from '../../services/Lang.service';
import ILangService from '../../services/ILang.service';

@Component(
selector: 'app-landing',
templateUrl: './landing.component.html',
styleUrls: ['./landing.component.less'],
providers: [
provide: ILangService, useClass: LangService
]
)

export class LandingComponent
private langService: ILangService
constructor(
private http: HttpClient,
_langService: ILangService;
)
this._langService = langService;







share|improve this answer




















    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53254749%2fhow-do-i-do-dependency-injection-with-service-in-angular-5%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    3 Answers
    3






    active

    oldest

    votes








    3 Answers
    3






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    0
    down vote



    accepted










    Updated Answer



    If you want to use different implementations for the same service you should create an InjectionToken<T> and provide the right implementation for your interface in your module declarations.



    Interface - lang.service.ts



    Create an injection token that will be recognized by the injector typed with ILangService interface



    export const LangService = new InjectionToken<ILangService>('LangService');

    export interface ILangService


    1st module - english.module.ts



    Provide EnglishLangService for the LangService injection token where EnglishLangService implements ILangService interface



    import LangService from './services/lang.service';
    import EnglishLangService from './services/english-lang.service';

    @NgModule(
    declarations: [ LandingComponent ],
    providers: [
    provide: LangService, useClass: EnglishLangService
    ]
    )
    export class EnglishModule


    2nd module - french.module.ts



    Provide FrenchLangService for the LangService injection token where FrenchLangService implements ILangService interface



    import LangService from './services/lang.service';
    import FrenchLangService from './services/french-lang.service';

    @NgModule(
    declarations: [ LandingComponent ],
    providers: [
    provide: LangService, useClass: FrenchLangService
    ]
    )
    export class FrenchModule


    Component - landing.component.ts



    This way you can inject LangService in your component and the injector will retrieve the implementation provided in your module



    import LangService from '../../services/lang.service';

    @Component(
    selector: 'app-landing',
    templateUrl: './landing.component.html',
    styleUrls: ['./landing.component.less']
    )
    export class LandingComponent
    constructor(
    private http: HttpClient,
    private langService: LangService,
    )



    Testing - mock-lang.service.ts



    When testing you will be able to provide your mock implementation the same way you provide the right implementation in your application modules



    import LangService from './services/lang.service';
    import MockLangService from './services/mock-lang.service';

    TestBed.configureTestingModule(
    providers: [
    provide: LangService, useClass: MockLangService ,
    ],
    );


    Original Answer



    You should import your service with the class instead of the interface



    import LangService from '../../services/lang.service';

    @Component(
    selector: 'app-landing',
    templateUrl: './landing.component.html',
    styleUrls: ['./landing.component.less']
    )
    export class LandingComponent
    constructor(
    private http: HttpClient,
    private langService: LangService;
    )



    Also don't forget to set the @Injectable() decorator on your service class declaration



    import Injectable from '@angular/core';

    @Injectable()
    export class LangService implements ILangService


    And of course, you have to provide the service to your module



    import LangService from './services/Lang.service';

    @NgModule(
    declarations: [
    AppComponent,
    LandingComponent,
    ],
    imports: [ ... ],
    providers: [
    LangService
    ],
    bootstrap: [AppComponent]
    )
    export class AppModule


    You can read about Angular Dependency Injection here: https://angular.io/guide/dependency-injection



    Another interesting link for advance service declarations: https://offering.solutions/blog/articles/2018/08/17/using-useclass-usefactory-usevalue-useexisting-with-treeshakable-providers-in-angular/






    share|improve this answer






















    • LangService is a implementation. In real case there will be few implementations like LangMockedSerives, langService_01, langService_02. Thereby landing component should know nothig about implementation and work with interfaces only.
      – mr_blond
      Nov 12 at 10:40










    • I updated the answer
      – j3ff
      Nov 12 at 15:43














    up vote
    0
    down vote



    accepted










    Updated Answer



    If you want to use different implementations for the same service you should create an InjectionToken<T> and provide the right implementation for your interface in your module declarations.



    Interface - lang.service.ts



    Create an injection token that will be recognized by the injector typed with ILangService interface



    export const LangService = new InjectionToken<ILangService>('LangService');

    export interface ILangService


    1st module - english.module.ts



    Provide EnglishLangService for the LangService injection token where EnglishLangService implements ILangService interface



    import LangService from './services/lang.service';
    import EnglishLangService from './services/english-lang.service';

    @NgModule(
    declarations: [ LandingComponent ],
    providers: [
    provide: LangService, useClass: EnglishLangService
    ]
    )
    export class EnglishModule


    2nd module - french.module.ts



    Provide FrenchLangService for the LangService injection token where FrenchLangService implements ILangService interface



    import LangService from './services/lang.service';
    import FrenchLangService from './services/french-lang.service';

    @NgModule(
    declarations: [ LandingComponent ],
    providers: [
    provide: LangService, useClass: FrenchLangService
    ]
    )
    export class FrenchModule


    Component - landing.component.ts



    This way you can inject LangService in your component and the injector will retrieve the implementation provided in your module



    import LangService from '../../services/lang.service';

    @Component(
    selector: 'app-landing',
    templateUrl: './landing.component.html',
    styleUrls: ['./landing.component.less']
    )
    export class LandingComponent
    constructor(
    private http: HttpClient,
    private langService: LangService,
    )



    Testing - mock-lang.service.ts



    When testing you will be able to provide your mock implementation the same way you provide the right implementation in your application modules



    import LangService from './services/lang.service';
    import MockLangService from './services/mock-lang.service';

    TestBed.configureTestingModule(
    providers: [
    provide: LangService, useClass: MockLangService ,
    ],
    );


    Original Answer



    You should import your service with the class instead of the interface



    import LangService from '../../services/lang.service';

    @Component(
    selector: 'app-landing',
    templateUrl: './landing.component.html',
    styleUrls: ['./landing.component.less']
    )
    export class LandingComponent
    constructor(
    private http: HttpClient,
    private langService: LangService;
    )



    Also don't forget to set the @Injectable() decorator on your service class declaration



    import Injectable from '@angular/core';

    @Injectable()
    export class LangService implements ILangService


    And of course, you have to provide the service to your module



    import LangService from './services/Lang.service';

    @NgModule(
    declarations: [
    AppComponent,
    LandingComponent,
    ],
    imports: [ ... ],
    providers: [
    LangService
    ],
    bootstrap: [AppComponent]
    )
    export class AppModule


    You can read about Angular Dependency Injection here: https://angular.io/guide/dependency-injection



    Another interesting link for advance service declarations: https://offering.solutions/blog/articles/2018/08/17/using-useclass-usefactory-usevalue-useexisting-with-treeshakable-providers-in-angular/






    share|improve this answer






















    • LangService is a implementation. In real case there will be few implementations like LangMockedSerives, langService_01, langService_02. Thereby landing component should know nothig about implementation and work with interfaces only.
      – mr_blond
      Nov 12 at 10:40










    • I updated the answer
      – j3ff
      Nov 12 at 15:43












    up vote
    0
    down vote



    accepted







    up vote
    0
    down vote



    accepted






    Updated Answer



    If you want to use different implementations for the same service you should create an InjectionToken<T> and provide the right implementation for your interface in your module declarations.



    Interface - lang.service.ts



    Create an injection token that will be recognized by the injector typed with ILangService interface



    export const LangService = new InjectionToken<ILangService>('LangService');

    export interface ILangService


    1st module - english.module.ts



    Provide EnglishLangService for the LangService injection token where EnglishLangService implements ILangService interface



    import LangService from './services/lang.service';
    import EnglishLangService from './services/english-lang.service';

    @NgModule(
    declarations: [ LandingComponent ],
    providers: [
    provide: LangService, useClass: EnglishLangService
    ]
    )
    export class EnglishModule


    2nd module - french.module.ts



    Provide FrenchLangService for the LangService injection token where FrenchLangService implements ILangService interface



    import LangService from './services/lang.service';
    import FrenchLangService from './services/french-lang.service';

    @NgModule(
    declarations: [ LandingComponent ],
    providers: [
    provide: LangService, useClass: FrenchLangService
    ]
    )
    export class FrenchModule


    Component - landing.component.ts



    This way you can inject LangService in your component and the injector will retrieve the implementation provided in your module



    import LangService from '../../services/lang.service';

    @Component(
    selector: 'app-landing',
    templateUrl: './landing.component.html',
    styleUrls: ['./landing.component.less']
    )
    export class LandingComponent
    constructor(
    private http: HttpClient,
    private langService: LangService,
    )



    Testing - mock-lang.service.ts



    When testing you will be able to provide your mock implementation the same way you provide the right implementation in your application modules



    import LangService from './services/lang.service';
    import MockLangService from './services/mock-lang.service';

    TestBed.configureTestingModule(
    providers: [
    provide: LangService, useClass: MockLangService ,
    ],
    );


    Original Answer



    You should import your service with the class instead of the interface



    import LangService from '../../services/lang.service';

    @Component(
    selector: 'app-landing',
    templateUrl: './landing.component.html',
    styleUrls: ['./landing.component.less']
    )
    export class LandingComponent
    constructor(
    private http: HttpClient,
    private langService: LangService;
    )



    Also don't forget to set the @Injectable() decorator on your service class declaration



    import Injectable from '@angular/core';

    @Injectable()
    export class LangService implements ILangService


    And of course, you have to provide the service to your module



    import LangService from './services/Lang.service';

    @NgModule(
    declarations: [
    AppComponent,
    LandingComponent,
    ],
    imports: [ ... ],
    providers: [
    LangService
    ],
    bootstrap: [AppComponent]
    )
    export class AppModule


    You can read about Angular Dependency Injection here: https://angular.io/guide/dependency-injection



    Another interesting link for advance service declarations: https://offering.solutions/blog/articles/2018/08/17/using-useclass-usefactory-usevalue-useexisting-with-treeshakable-providers-in-angular/






    share|improve this answer














    Updated Answer



    If you want to use different implementations for the same service you should create an InjectionToken<T> and provide the right implementation for your interface in your module declarations.



    Interface - lang.service.ts



    Create an injection token that will be recognized by the injector typed with ILangService interface



    export const LangService = new InjectionToken<ILangService>('LangService');

    export interface ILangService


    1st module - english.module.ts



    Provide EnglishLangService for the LangService injection token where EnglishLangService implements ILangService interface



    import LangService from './services/lang.service';
    import EnglishLangService from './services/english-lang.service';

    @NgModule(
    declarations: [ LandingComponent ],
    providers: [
    provide: LangService, useClass: EnglishLangService
    ]
    )
    export class EnglishModule


    2nd module - french.module.ts



    Provide FrenchLangService for the LangService injection token where FrenchLangService implements ILangService interface



    import LangService from './services/lang.service';
    import FrenchLangService from './services/french-lang.service';

    @NgModule(
    declarations: [ LandingComponent ],
    providers: [
    provide: LangService, useClass: FrenchLangService
    ]
    )
    export class FrenchModule


    Component - landing.component.ts



    This way you can inject LangService in your component and the injector will retrieve the implementation provided in your module



    import LangService from '../../services/lang.service';

    @Component(
    selector: 'app-landing',
    templateUrl: './landing.component.html',
    styleUrls: ['./landing.component.less']
    )
    export class LandingComponent
    constructor(
    private http: HttpClient,
    private langService: LangService,
    )



    Testing - mock-lang.service.ts



    When testing you will be able to provide your mock implementation the same way you provide the right implementation in your application modules



    import LangService from './services/lang.service';
    import MockLangService from './services/mock-lang.service';

    TestBed.configureTestingModule(
    providers: [
    provide: LangService, useClass: MockLangService ,
    ],
    );


    Original Answer



    You should import your service with the class instead of the interface



    import LangService from '../../services/lang.service';

    @Component(
    selector: 'app-landing',
    templateUrl: './landing.component.html',
    styleUrls: ['./landing.component.less']
    )
    export class LandingComponent
    constructor(
    private http: HttpClient,
    private langService: LangService;
    )



    Also don't forget to set the @Injectable() decorator on your service class declaration



    import Injectable from '@angular/core';

    @Injectable()
    export class LangService implements ILangService


    And of course, you have to provide the service to your module



    import LangService from './services/Lang.service';

    @NgModule(
    declarations: [
    AppComponent,
    LandingComponent,
    ],
    imports: [ ... ],
    providers: [
    LangService
    ],
    bootstrap: [AppComponent]
    )
    export class AppModule


    You can read about Angular Dependency Injection here: https://angular.io/guide/dependency-injection



    Another interesting link for advance service declarations: https://offering.solutions/blog/articles/2018/08/17/using-useclass-usefactory-usevalue-useexisting-with-treeshakable-providers-in-angular/







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Nov 12 at 17:42

























    answered Nov 12 at 1:47









    j3ff

    1,82311125




    1,82311125











    • LangService is a implementation. In real case there will be few implementations like LangMockedSerives, langService_01, langService_02. Thereby landing component should know nothig about implementation and work with interfaces only.
      – mr_blond
      Nov 12 at 10:40










    • I updated the answer
      – j3ff
      Nov 12 at 15:43
















    • LangService is a implementation. In real case there will be few implementations like LangMockedSerives, langService_01, langService_02. Thereby landing component should know nothig about implementation and work with interfaces only.
      – mr_blond
      Nov 12 at 10:40










    • I updated the answer
      – j3ff
      Nov 12 at 15:43















    LangService is a implementation. In real case there will be few implementations like LangMockedSerives, langService_01, langService_02. Thereby landing component should know nothig about implementation and work with interfaces only.
    – mr_blond
    Nov 12 at 10:40




    LangService is a implementation. In real case there will be few implementations like LangMockedSerives, langService_01, langService_02. Thereby landing component should know nothig about implementation and work with interfaces only.
    – mr_blond
    Nov 12 at 10:40












    I updated the answer
    – j3ff
    Nov 12 at 15:43




    I updated the answer
    – j3ff
    Nov 12 at 15:43












    up vote
    0
    down vote













    service.ts



    import Injectable from '@angular/core';
    import HttpClient, Response, RequestOptions, Headers from '@angular/common/http';
    import Observable from 'rxjs/Observable';
    import 'rxjs/add/operator/map';
    import 'rxjs/add/operator/catch';
    import 'rxjs/add/observable/throw';

    export interface ILangService


    @Injectable()
    export class LangService implements ILangService

    constructor(private http: HttpClient) <-- httpclient for angular6


    getData(): Observable<any>
    return this.http.get('https://..../');
    .map(this.extractData)
    .catch(this.handleError);


    private extractData(res: Response) ;


    private handleError(error: any)
    const errMsg = (error.message) ? error.message :
    error.status ? `$error.status - $error.statusText` : 'Server error';
    console.error(errMsg);
    console.log('Error....!');
    return Observable.throw(errMsg);




    Component:-



    import LangService from '../../services/lang.service'; <-- Import sevice here

    @Component(
    selector: 'app-landing',
    templateUrl: './landing.component.html',
    styleUrls: ['./landing.component.less']
    )

    export class LandingComponent
    constructor(
    private http: HttpClient,
    _langService: LangService <--- service
    )

    ngOnInit()
    let thisx = this;
    this._langService.getData().subscribe(
    function (success)
    // alert here on success
    alert (success);
    ,
    error => console.log('Getting Server Data Error :: ' +
    JSON.stringify(error)));







    share|improve this answer






















    • LangService is a implementation. In real case there will be few implementations like LangMockedSerives, langService_01, langService_02. Thereby landing component should know nothig about implementation and work with interfaces only.
      – mr_blond
      Nov 12 at 10:40














    up vote
    0
    down vote













    service.ts



    import Injectable from '@angular/core';
    import HttpClient, Response, RequestOptions, Headers from '@angular/common/http';
    import Observable from 'rxjs/Observable';
    import 'rxjs/add/operator/map';
    import 'rxjs/add/operator/catch';
    import 'rxjs/add/observable/throw';

    export interface ILangService


    @Injectable()
    export class LangService implements ILangService

    constructor(private http: HttpClient) <-- httpclient for angular6


    getData(): Observable<any>
    return this.http.get('https://..../');
    .map(this.extractData)
    .catch(this.handleError);


    private extractData(res: Response) ;


    private handleError(error: any)
    const errMsg = (error.message) ? error.message :
    error.status ? `$error.status - $error.statusText` : 'Server error';
    console.error(errMsg);
    console.log('Error....!');
    return Observable.throw(errMsg);




    Component:-



    import LangService from '../../services/lang.service'; <-- Import sevice here

    @Component(
    selector: 'app-landing',
    templateUrl: './landing.component.html',
    styleUrls: ['./landing.component.less']
    )

    export class LandingComponent
    constructor(
    private http: HttpClient,
    _langService: LangService <--- service
    )

    ngOnInit()
    let thisx = this;
    this._langService.getData().subscribe(
    function (success)
    // alert here on success
    alert (success);
    ,
    error => console.log('Getting Server Data Error :: ' +
    JSON.stringify(error)));







    share|improve this answer






















    • LangService is a implementation. In real case there will be few implementations like LangMockedSerives, langService_01, langService_02. Thereby landing component should know nothig about implementation and work with interfaces only.
      – mr_blond
      Nov 12 at 10:40












    up vote
    0
    down vote










    up vote
    0
    down vote









    service.ts



    import Injectable from '@angular/core';
    import HttpClient, Response, RequestOptions, Headers from '@angular/common/http';
    import Observable from 'rxjs/Observable';
    import 'rxjs/add/operator/map';
    import 'rxjs/add/operator/catch';
    import 'rxjs/add/observable/throw';

    export interface ILangService


    @Injectable()
    export class LangService implements ILangService

    constructor(private http: HttpClient) <-- httpclient for angular6


    getData(): Observable<any>
    return this.http.get('https://..../');
    .map(this.extractData)
    .catch(this.handleError);


    private extractData(res: Response) ;


    private handleError(error: any)
    const errMsg = (error.message) ? error.message :
    error.status ? `$error.status - $error.statusText` : 'Server error';
    console.error(errMsg);
    console.log('Error....!');
    return Observable.throw(errMsg);




    Component:-



    import LangService from '../../services/lang.service'; <-- Import sevice here

    @Component(
    selector: 'app-landing',
    templateUrl: './landing.component.html',
    styleUrls: ['./landing.component.less']
    )

    export class LandingComponent
    constructor(
    private http: HttpClient,
    _langService: LangService <--- service
    )

    ngOnInit()
    let thisx = this;
    this._langService.getData().subscribe(
    function (success)
    // alert here on success
    alert (success);
    ,
    error => console.log('Getting Server Data Error :: ' +
    JSON.stringify(error)));







    share|improve this answer














    service.ts



    import Injectable from '@angular/core';
    import HttpClient, Response, RequestOptions, Headers from '@angular/common/http';
    import Observable from 'rxjs/Observable';
    import 'rxjs/add/operator/map';
    import 'rxjs/add/operator/catch';
    import 'rxjs/add/observable/throw';

    export interface ILangService


    @Injectable()
    export class LangService implements ILangService

    constructor(private http: HttpClient) <-- httpclient for angular6


    getData(): Observable<any>
    return this.http.get('https://..../');
    .map(this.extractData)
    .catch(this.handleError);


    private extractData(res: Response) ;


    private handleError(error: any)
    const errMsg = (error.message) ? error.message :
    error.status ? `$error.status - $error.statusText` : 'Server error';
    console.error(errMsg);
    console.log('Error....!');
    return Observable.throw(errMsg);




    Component:-



    import LangService from '../../services/lang.service'; <-- Import sevice here

    @Component(
    selector: 'app-landing',
    templateUrl: './landing.component.html',
    styleUrls: ['./landing.component.less']
    )

    export class LandingComponent
    constructor(
    private http: HttpClient,
    _langService: LangService <--- service
    )

    ngOnInit()
    let thisx = this;
    this._langService.getData().subscribe(
    function (success)
    // alert here on success
    alert (success);
    ,
    error => console.log('Getting Server Data Error :: ' +
    JSON.stringify(error)));








    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Nov 12 at 3:24

























    answered Nov 12 at 3:18









    Mahi

    855319




    855319











    • LangService is a implementation. In real case there will be few implementations like LangMockedSerives, langService_01, langService_02. Thereby landing component should know nothig about implementation and work with interfaces only.
      – mr_blond
      Nov 12 at 10:40
















    • LangService is a implementation. In real case there will be few implementations like LangMockedSerives, langService_01, langService_02. Thereby landing component should know nothig about implementation and work with interfaces only.
      – mr_blond
      Nov 12 at 10:40















    LangService is a implementation. In real case there will be few implementations like LangMockedSerives, langService_01, langService_02. Thereby landing component should know nothig about implementation and work with interfaces only.
    – mr_blond
    Nov 12 at 10:40




    LangService is a implementation. In real case there will be few implementations like LangMockedSerives, langService_01, langService_02. Thereby landing component should know nothig about implementation and work with interfaces only.
    – mr_blond
    Nov 12 at 10:40










    up vote
    0
    down vote













    LangService shoul be removed from app.module.ts providers:



    @NgModule(
    declarations: [
    AppComponent,
    LandingComponent,
    ],
    imports: [
    BrowserModule,
    HttpClientModule,
    RouterModule.forRoot([
    path: '', component: LandingComponent ,
    ], useHash: false ),
    ],
    providers: ,
    bootstrap: [AppComponent]
    )
    export class AppModule


    And interface should be added to providers in component:



    import LangService from '../../services/Lang.service';
    import ILangService from '../../services/ILang.service';

    @Component(
    selector: 'app-landing',
    templateUrl: './landing.component.html',
    styleUrls: ['./landing.component.less'],
    providers: [
    provide: ILangService, useClass: LangService
    ]
    )

    export class LandingComponent
    private langService: ILangService
    constructor(
    private http: HttpClient,
    _langService: ILangService;
    )
    this._langService = langService;







    share|improve this answer
























      up vote
      0
      down vote













      LangService shoul be removed from app.module.ts providers:



      @NgModule(
      declarations: [
      AppComponent,
      LandingComponent,
      ],
      imports: [
      BrowserModule,
      HttpClientModule,
      RouterModule.forRoot([
      path: '', component: LandingComponent ,
      ], useHash: false ),
      ],
      providers: ,
      bootstrap: [AppComponent]
      )
      export class AppModule


      And interface should be added to providers in component:



      import LangService from '../../services/Lang.service';
      import ILangService from '../../services/ILang.service';

      @Component(
      selector: 'app-landing',
      templateUrl: './landing.component.html',
      styleUrls: ['./landing.component.less'],
      providers: [
      provide: ILangService, useClass: LangService
      ]
      )

      export class LandingComponent
      private langService: ILangService
      constructor(
      private http: HttpClient,
      _langService: ILangService;
      )
      this._langService = langService;







      share|improve this answer






















        up vote
        0
        down vote










        up vote
        0
        down vote









        LangService shoul be removed from app.module.ts providers:



        @NgModule(
        declarations: [
        AppComponent,
        LandingComponent,
        ],
        imports: [
        BrowserModule,
        HttpClientModule,
        RouterModule.forRoot([
        path: '', component: LandingComponent ,
        ], useHash: false ),
        ],
        providers: ,
        bootstrap: [AppComponent]
        )
        export class AppModule


        And interface should be added to providers in component:



        import LangService from '../../services/Lang.service';
        import ILangService from '../../services/ILang.service';

        @Component(
        selector: 'app-landing',
        templateUrl: './landing.component.html',
        styleUrls: ['./landing.component.less'],
        providers: [
        provide: ILangService, useClass: LangService
        ]
        )

        export class LandingComponent
        private langService: ILangService
        constructor(
        private http: HttpClient,
        _langService: ILangService;
        )
        this._langService = langService;







        share|improve this answer












        LangService shoul be removed from app.module.ts providers:



        @NgModule(
        declarations: [
        AppComponent,
        LandingComponent,
        ],
        imports: [
        BrowserModule,
        HttpClientModule,
        RouterModule.forRoot([
        path: '', component: LandingComponent ,
        ], useHash: false ),
        ],
        providers: ,
        bootstrap: [AppComponent]
        )
        export class AppModule


        And interface should be added to providers in component:



        import LangService from '../../services/Lang.service';
        import ILangService from '../../services/ILang.service';

        @Component(
        selector: 'app-landing',
        templateUrl: './landing.component.html',
        styleUrls: ['./landing.component.less'],
        providers: [
        provide: ILangService, useClass: LangService
        ]
        )

        export class LandingComponent
        private langService: ILangService
        constructor(
        private http: HttpClient,
        _langService: ILangService;
        )
        this._langService = langService;








        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 12 at 12:17









        mr_blond

        15411




        15411



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53254749%2fhow-do-i-do-dependency-injection-with-service-in-angular-5%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            這個網誌中的熱門文章

            What does pagestruct do in Eviews?

            Dutch intervention in Lombok and Karangasem

            Channel Islands