Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use service inside model class

I have created a model class for movies in my project which contains the following

//movie/model.ts
export class Movie {

  title:string;
  overview:string;
  id:string;
  seasons:any[];

  constructor(obj: any) {

        this.id = obj.id;
        this.overview = obj.overview;
        this.title = obj.title;

    }
}

Also i have made a service which makes all the http calls to fetch data from an api.

//api.service.ts
import { Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';
import 'rxjs/Rx';

import {Movie} from './movie/model';

@Injectable()
export class ApiService {

  constructor(private http: Http) {}

  getMovie(id):{

    let url = this.Api_Url + '/movies/' + id + "?extended=full,images";

    return this.http.get(url, { headers: this.headers })
      .map(d => d.json())
      .map(d => new Movie(d))
      .toPromise()
  }

  getActors(){...}

Everything works ok, i provide one instance of api service in my bootstrap function and i can use it in every component to get a movie. Although i would like to have this instance of api service in my movie class but i dont know how to tell angular to provide it. This is what i want, and what i have tried.

//movie/model.ts

import {ApiService} from "../api.service";
export class Movie {

  title:string;
  overview:string;
  id:string;
  seasons:any[];

  constructor(obj: any, private api: ApiService) {}

  getActors(): { 
    this.api.getActors()
    //api is null 
  }
}

I also tried to @Inject(api) and create it with new but it says it depends on http service. So how can i tell angular i need this api instance on my class when this class is not a component or service but just a simple es6 class?? Is this an anti pattern?? Because i used to do the same thing in angular 1 and everything worked as expected.

like image 661
Alex Michailidis Avatar asked Oct 31 '22 02:10

Alex Michailidis


1 Answers

In fact, to be able to inject something in a class with Angular2, you need a decorator and a corresponding provider registered. If you instantiate the class by your own, you can't leverage dependency injection.

That being said, you can provide the dependencies you need when instantiating your class:

@Injectable()
export class ApiService {
  constructor(private http: Http) {}

  getMovie(id):{
    let url = this.Api_Url + '/movies/' + id + "?extended=full,images";

    return this.http.get(url, { headers: this.headers })
      .map(d => d.json())
      .map(d => new Movie(d, this)) // <----
      .toPromise()
  }

  getActors(){...}
like image 150
Thierry Templier Avatar answered Nov 12 '22 20:11

Thierry Templier