简体   繁体   中英

TypeScript Constructor with multiple parameters and an injected item

I have a typescript class as below:

export class ImageItem{
    constructor(public Id: number, public ImageUrl: string, public Caption: string, public Description: string, private _sanitizer: DomSanitizer)
    {
    }
}

all the constructor's parameters are properties that are related to that class but the last item is a class which is injected into my class. My problem is if I want to create an object of this class I want to do something as below:

var a=new ImageItem(1, 'image1', 'http://aaa.com/aa.jpg', '')

But it gives me an error because of the injected item. I was wondering how I should solve this issue.

What you need is a factory service that is able to create instances of this kind of class and at the same time injects the properties you would like to have injected.

It would look something like this.

The image-item.ts defines a simple class:

import { DomSanitizer } from '@angular/platform-browser';

export class ImageItem {
    constructor(public Id: number, public ImageUrl: string, public Caption: string, 
                  public Description: string, private _sanitizer: DomSanitizer) {
    }
}

The factory is an injectable service that injects the DomSanitizer and has a method able to create instances of ImageItem .

import { Injectable } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
import { ImageItem } from './image-item';

@Injectable()
export class ImageItemFactoryService {

  constructor(private domSanitizer: DomSanitizer) { }

  public createImageItem(id: number, description: string) {
    return new ImageItem(id, '', '', description, this.domSanitizer);
  }
}

The app.component.ts imports the factory as a provider and uses it to create instances of ImageItem .

import { Component } from '@angular/core';
import { ImageItem } from './image-item';
import { ImageItemFactoryService } from './image-item-factory.service';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [ImageItemFactoryService]
})
export class AppComponent {
  private item: ImageItem = null;
  constructor(public imageItemFactory: ImageItemFactoryService) {
    this.item = imageItemFactory.createImageItem(1, 'something');
  }
}

In angularjs(1) it was possible to use the injector in order to create an instance and it was possible at the same time to give some local values to be used during injection.

In angular (2) however the Injector service no longer provides that functionality.

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