RC7 is missing the necessary HTTP_PROVIDERS for the resolveAndCreate HTTP method in Angular2

During the time of RC4, I was able to create my own custom http instance using a function like this:

export function createHTTP(url:string, headers?:Headers){
  let injector = ReflectiveInjector.resolveAndCreate([
    myHttp,
    {provide:'defaultUrl', useValue:url},
    {provide:'defaultHeaders', useValue:headers || new Headers()},
    
    // Here is where HTTP_PROVIDERS used to be included
  ])
  return injector.get(myHttp)
}

The 'myHttp' class served as a wrapper for Http.

@Injectable()
export class myHttp{
  constructor(@Inject('defaultUrl) private url:string, @Inject('defaultHeaders') private headers:Headers, private http:Http){}

  get()
  put()...
}

With HTTP_PROVIDERS now deprecated and removed, how can I achieve the same functionality?

Thanks!

Answer №1

@NgModule({
  imports: [HttpModule],
  ...
})
class AppModule {}

Alternatively, you can extract the definition of HTTP_PROVIDERS from the Angular2 source code and incorporate it into your own source for usage.

const HTTP_PROVIDERS = [
    {provide: Http, useFactory: 
      (xhrBackend: XHRBackend, requestOptions: RequestOptions): Http =>
          new Http(xhrBackend, requestOptions), 
          deps: [XHRBackend, RequestOptions]},
    BrowserXhr,
    {provide: RequestOptions, useClass: BaseRequestOptions},
    {provide: ResponseOptions, useClass: BaseResponseOptions},
    XHRBackend,
    {provide: XSRFStrategy, useFactory: () => new CookieXSRFStrategy()},
];

Another option is to manually construct an injector with these providers:

let resolvedProviders = ReflectiveInjector.resolve(HTTP_PROVIDERS);
let injector = ReflectiveInjector.fromResolvedProviders(resolvedProviders, /* this.injector (parent injector if any) */ );
var http = child.get(Http);

For more information, refer to Inject Http manually in angular 2

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The operation to append in Angular/Mutation was unsuccessful because parameter 2 is not a valid type of 'Blob' for FormData

Currently, I have set up my project with Angular/Apollo (Graphql) on the client side and NestJS on the server side. When it comes to uploading files to the server, I am utilizing the 'graphql-upload-ts' package for this task. Interestingly, the ...

Tips for transforming a Json array into an object in Angular 5

I am working with a Json array that looks like this: [{"name":"ip","children":{"label":"ip","value":"","type":"text","validation":"{ required: true}"}} ,{"name":"test","children":{"label":"test","value":"","type":"text","validation":"{ required: true}"}} ...

Issue with setting values in Angular2 when using IE 11 and shims included

First off, I want to clarify that I have indeed added the shims in my index.html file. <script src="node_modules/es6-shim/es6-shim.min.js"></script> <script src="node_modules/systemjs/dist/system-polyfills.js"></script> <script ...

Angular is showing an error stating that the type 'EventEmitter' is not generic

As I follow along with a tutorial, I've come across the use of EventEmitter. The code snippet provided in the tutorial is as follows: @Output() ratingClicked: EventEmitter<string> = new EventEmitter<string>(); However, my Visual ...

Error: passport-local-mongoose does not have a createStrategy or authenticate function

Currently, I am working on enhancing features of a starter project available at this repository. The specific task at hand involves integrating user login functionality using passport-local-mongoose. In my attempts to utilize different strategies for impl ...

The TypeScript error message is saying that it cannot find the property 'push' of an undefined value, resulting in a error within the

Issue: Unable to access property 'push' of undefined in [null]. class B implements OnInit { messageArr: string[]; ngOnInit() { for(let i=0; i<5; i++) { this.messageArr.push("bbb"); } } } ...

Develop a versatile class for storing an array of key-value pairs (dictionary) using TypeScript

I am looking to implement a Dictionary class in my application. I have created a class with an Array of KeyValuePair to store my list. export class KeyValuePair<TKey, TVal>{ key:TKey; value:TVal; constructor(key:TKey, val:TVal){ this.key = key; ...

Convert checkbox choices to strings stored in an array within an object

I have a intricate object structure JSON{ alpha{ array1[ obj1{}, obj2{} ] } } In addition to array1, I need to include another array: array2 that will only consist of strin ...

Issue encountered while generating menu using Angular's Material framework

In my Angular project, I am working on creating a right-side menu with specific functionalities. While the Home and Photo menus work perfectly, I am encountering an issue with the Admin menu. I intend to have 2 submenus open when clicking on the Admin tab, ...

Implementing Azure Active Directory Authentication for Angular 4 or Angular 2 - Retrieving Access Tokens

I'm in the process of authenticating an Angular 4/Angular 2 app with Azure Active Directory to obtain a token code for passing as a Bearer token when calling a REST API. For this purpose, I've utilized 'ng2-adal' available at https://g ...

Iterate over a collection of HTML elements to assign a specific class to one element and a different class to the remaining elements

Forgive me if this is a silly question, but I have a function named selectFace(face); The idea is that when an item is clicked, it should add one class to that item and another class to all the other items. This is what I currently have: HTML <div c ...

The PrimeNG table fails to refresh upon initial modification

I'm working with a prime-ng table of shops, where I have the ability to remove and add shops to a list. The scenario: Whenever a shop is added, the ChildComponent emits an event to the ParentComponent, which then adds the shop to the list and updates ...

Switching the LOCALE_ID in angular at runtime

One example of extensive localization support is found in the FB region setting, which accommodates hundreds of locales. How can we replicate this functionality in Angular? Would this require us to manually register all supported locales during development ...

Tips for validating form input upon submission in Angular 6

Within my Angular application, I have successfully implemented form validators. However, I am aiming to trigger form validation specifically upon submission. This means that when the user clicks on the submit button and the form is invalid, the errors indi ...

How can we ensure file uploads are validated when using class-validator?

Recently, I've been utilizing the wonderful class-validator package to validate data. One specific validation task I'm working on is validating a file upload, ensuring that the file is not empty and ideally confirming that it is an image file. H ...

Unable to employ the .some() method with an array consisting of objects

I am currently attempting to determine whether my array of objects contains an attribute with a specific value. I wanted to use the array.some() method instead of a foreach loop, but I keep encountering an error: Error TS2345: Argument of type '(ele ...

nodemon and ts-node not working as expected, failing to automatically recompile

I have been working on creating a REST API using express+ts-node. Following various online tutorials, I managed to set everything up and when I run the app using npm run dev, it works perfectly fine. However, I am facing an issue where it is not automatica ...

What are the steps to prevent exceptions from being displayed when an Angular project times out?

Despite the absence of a debugger or breakpoints provided, the execution halts here whenever the Angular project is logged out due to timeout. https://i.sstatic.net/OFsvI.png ...

The template for the AppComponent is experiencing an error

Every time I run 'ng serve' command, I encounter the following error: src/app/add-dog/add-dog.component.html:8:36: 8 │ <input type="text" [(ngModel)]="formData.breed" /> ╵ ...

Setting an array of objects using TypeScript in the useState hook: A step-by-step guide

const response = { results: { items: [ { name: 'item1', }, { name: 'item2', }, { name: 'item3', }, { ...