Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject Http manually in Angular 2

Tags:

angular

I have created a Base Model in which I have all the common functions to fetch data and post or put the data. Actually what a service does in Angular but I don't want a service.

Now what I am planning to do is The base model will extended by all the modules in my system each module having its base endpoint to get data from the API. Now here's the problem If I inject the Http service in base model and the user model extends the Base model, Now to create a object of base model I need to pass the object of Http which I am unable.

export class BaseModel {
constructor (http: Http) {}

fetch() {
let params = {
            "includes": this.includes,
            "page": page,
            "filters" : this.filters,
            "order" : this.orderDirection + this.orderColumn
        };

        return this.api.get("/"+this.endpoint, params)
            .map(
                (response: any) => {
                    let total = response.meta.total;
                    let current = response.meta.current;

                    let min = current - 5;
                    let max = current + 5;

                    if (min < 1) {
                        min = 1;
                    }

                    if (max > total) {
                        max = total;
                    }
                    else if (max < 10) {
                        if(total < 10) {
                            max = total;
                        }else {
                            max = 10;
                        }
                    }

                    let pages : number[] = [];

                    for (let i = min; i <= max; i++) {
                        pages.push(i);
                    }

                    this.pages = pages;

                    return response
                }
            );
}
}

Now my User Model

export class User extends BaseModel {

public id : number;
    public username : string;
    public email : string;
    public password : string;
    public passwordConfirmation : string;
    public details : UserDetail = new UserDetail();
    public type : string;
    public status : string;
    public profileImage : string;
    public profileImageUrl : string;
    public crop : Object = {};
    public lastLogin : string;
    public numberOfLogin : string;
    public joinDate : string;
    public registerType : string = "web";

    public static create(response : any) {

        if (response === undefined || response === null) {
            return response;
        }

        let details = new UserDetail();

        if (response.details) {
            details = UserDetail.create(response.details);
        }

        let user = new User(); //error parameter required
        user.id = response.id;
        user.username = response.username;
        user.email = response.email;
        user.status = response.status;
        user.type = response.type;
        user.details.id = response.details.id;
        user.details = details;
        user.profileImageUrl = response.profile_image_url;
        user.joinDate = response.created_at;
        user.registerType = response.register_type;

        return user;
    }

}
like image 941
Sushant Yadav Avatar asked Aug 31 '16 07:08

Sushant Yadav


People also ask

What does @inject do in Angular?

The @Injectable() decorator defines a class as a service in Angular and allows Angular to inject it into a component as a dependency. Likewise, the @Injectable() decorator indicates that a component, class, pipe, or NgModule has a dependency on a service. The injector is the main mechanism.

Where do you inject HttpClient in service file?

Before you can use HttpClient , you need to import the Angular HttpClientModule . Most apps do so in the root AppModule . You can then inject the HttpClient service as a dependency of an application class, as shown in the following ConfigService example.

How is Angular Dependency Injection implemented?

The first step is to add the @Injectable decorator to show that the class can be injected. The next step is to make it available in the DI by providing it. A dependency can be provided in multiple places: At the Component level, using the providers field of the @Component decorator.

What is HTTP in Angular?

$http is an AngularJS service for reading data from remote servers.


2 Answers

UPDATE (final)

constructor() {
  let injector = ReflectiveInjector.resolveAndCreate([
    Http,
    BrowserXhr,
    {provide: RequestOptions, useClass: BaseRequestOptions},
    {provide: ResponseOptions, useClass: BaseResponseOptions},
    {provide: ConnectionBackend, useClass: XHRBackend},
    {provide: XSRFStrategy, useFactory: () => new CookieXSRFStrategy()},
  ]);
  this.http = injector.get(Http);
}

ORIGINAL (RC.x)

constructor() {
  let injector = ReflectiveInjector.resolveAndCreate([HTTP_PROVIDERS]);
  this.http = injector.get(Http);
}

This creates a new injector (independent of the one used by the rest of your Angular2 app. This isn't necessarily a problem, you just should be aware of it.

See also angular2 resolveAndCreate HTTP - missing HTTP_PROVIDERS in RC7

like image 126
Günter Zöchbauer Avatar answered Nov 15 '22 17:11

Günter Zöchbauer


Ugly solution which works in Angular 2.1

import {ReflectiveInjector} from '@angular/core';
import {Http, HttpModule} from "@angular/http";

const providers = (<any>HttpModule).decorators[0].args[0].providers;
const injector = ReflectiveInjector.resolveAndCreate(providers);
const http = injector.get(Http);
like image 34
Erik van Velzen Avatar answered Nov 15 '22 18:11

Erik van Velzen