简体   繁体   中英

Angular 6 Dependency Injection in a Class

I have a problem of knowledge about dependency injection with Angular 6.

The scene is the following :

A single class (used as Model) :

import { NgModule } from '@angular/core';
import { ContactProviderService } from './../services/contact-provider.service';
import { SuiviInterface } from './../interfaces/suiviinterface';
import { WebapiService } from './../services/webapi.service';
import { QuotationInterface } from './../interfaces/quotationinterface';

import { DeserializableInterface } from './../interfaces/deserializableinterface';

import { MomentDate } from './momentdate';
import { User } from './user';
import { Feature } from './feature';
import { Suivi } from './suivi';

@NgModule({
  providers: [
    WebapiService,
    ContactProviderService
  ]
})

export class Quotation implements QuotationInterface, DeserializableInterface<Quotation> {
  public id: number;

  public date: MomentDate;

  public user: User;

  public feature: Feature;

  public dateValidation?: MomentDate;

 public dateProposition?: MomentDate;

 public dateAcceptation?: MomentDate;

 public isArchive: Boolean;

 public isDeleted: Boolean;

 public numParcelle: string;

 public commentaire: string;

 public lead?: string;

 public suivi: Array<Suivi>;

 public propositionDone: boolean = false;

 private nbAttributions: number = 0;
 private nbPropositions: number = 0;

 public constructor(
    private webApi: WebapiService,
    private contactProvider: ContactProviderService) {
    this.dateValidation = null;
  }

 ... some getters / setters

public deserialize(input: any): Quotation {

    Object.assign(this, input);

    // some other stuff

   return this;
 }
 }
 }

In this class, both WebapiService and ContactProviderService are Injectable, so, i thaught that it was self sufficient to inject them in the contuctor of the class.

I added @NgModule to try... but when i create an instance of a Quotation, have the following error :

Expected 2 arguments but got 0

What i'm doing wrong ?

Thx,

Jean-Luc

I think it's because you're missing the @Component Decorator, and then inside there you can provide your services if they're unique to that component. (Wont be shared with entire app if declared in component)

@Component({
   selector: 'some-selector',
   templateUrl: ['./'],
   stylesUrl: ['./'],
   providers:[ WebapiService, ContactProviderService ]
})

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