Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 987
Nick Mehrdad Babaki Avatar asked Aug 19 '17 11:08

Nick Mehrdad Babaki


1 Answers

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.

like image 196
toskv Avatar answered Oct 14 '22 05:10

toskv