mhaken
mhaken

Reputation: 1125

Angular 4 / TypeScript HttpModule Use In Class

I have a TypeScript class in an Angular 4 app that I want to do something like this:

Import { Http } from '@angular/http';

export class Request {
  public url: string;
  public services: string;
  public regions: string;
  public start: Date;
  public end: Date;
  public output: string;

  constructor(private http: Http) {
    this.url = "https://someurl.com";
    this.services = "All";
    this.regions = "All";
    this.output = "json";
  }

  public Submit() {
    this.http.get(this.url).subscribe();
    ...
  }
}

This would be all well and fine, except in a component, part of my model is the Request class

@Component({
selector: "app-request",
styleUrls: [
    './request.component.css'
],
templateUrl: './request.component.html'
})
export class RequestComponent implements OnInit {

  request: Request = new Request();

  ...
}

Then the template has several inputs that look like this:

<select name="output" id="output" [(ngModel)]="request.output">
        <option *ngFor="let output of outputs" [ngValue]="output">{{output}}</option>
</select>

The request object has a bunch of properties that are set as part of ngModel and it seems natural that the class object would have a submit method that I can just call directly from the component. However, the new Request() fails as it is expecting the Http module object as a parameter. Is this approach not feasible, or how do I inject the Http module as a parameter here?

Upvotes: 1

Views: 497

Answers (1)

Rahul
Rahul

Reputation: 5774

Ideally, you should not be wrapping up your class and service together (maintenance point of view).

However, to answer your question. You will have to make your Request (hybrid service??) an Injectable with annotation @Injectable() and make it accessible by providing it into module.

Import { Http } from '@angular/http';
Import { Injectable } from '@angular/core';

@Injectable()
export class Request {
  public url: string;
  public services: string;
  public regions: string;
  public start: Date;
  public end: Date;
  public output: string;

  constructor(private http: Http) {
    this.url = "https://someurl.com";
    this.services = "All";
    this.regions = "All";
    this.output = "json";
  }

  public Submit() {
    this.http.get(this.url).subscribe();
    ...
  }
}

Now you can get instance in your component constructor.

@Component({
selector: "app-request",
styleUrls: [
    './request.component.css'
],
templateUrl: './request.component.html'
})
export class RequestComponent implements OnInit {

  request: Request;

  constructor(
    request:Request){}

}

That's a standard angular feature. Ideally, you should make services injectable.

Upvotes: 3

Related Questions