Angular 2 rc4's HTTP requests are generating uncaught exceptions (in promise)

Is there a change in Angular 2 HTTP service after upgrading to Angular 2 rc4?

I have spent the entire day going through Angular HTTP client documentation and searching on Stack Overflow, but I can't seem to find the solution to my problem.

Here are snippets of my code implementation and the error I am encountering. Can anyone please help me figure out what I am doing wrong?

Below is my code:

    import { Restaurant } from '../index'
    import { Http, Headers, RequestOptions, Response } from '@angular/http';
    import { Injectable } from '@angular/core';

    import 'rxjs/Rx';
    import { Observable } from 'rxjs/Observable';

@Injectable() 
export class RestaurantService {
    constructor(private _http: Http){}

    addRestaurant(restaurant: Restaurant): Observable<Restaurant> {
        let body = JSON.stringify({restaurant});
        let headers = new Headers({ 'Content-Type':'application/json'});
        let options = new RequestOptions({ headers: headers});
        console.log(body);
        return this._http.post('http://localhost:3000/restaurant', body, options)
            .map(this.extractData)
            .catch(this.errorHandler)
    }


    private extractData(res: Response) {
       let body = res.json();
       return body;
    }

    private errorHandler(error:any) {
       return Observable.throw(error.json());
     }
    }

The service is implemented in my code below:

import { Component, OnInit, OnDestroy } from '@angular/core';
import { REACTIVE_FORM_DIRECTIVES, FormArray,  FORM_DIRECTIVES, FormControl, FormGroup } from '@angular/forms';
import { Restaurant } from './index';
import { RestaurantService } from '../../index';

@Component({
    moduleId: module.id,
    selector: 'sd-restaurant-form',
    templateUrl: 'restaurant-form.component.html',
    styleUrls: ['restaurant-form.component.html'],
    directives: [REACTIVE_FORM_DIRECTIVES]
})
export class RestaurantFormComponent implements OnInit, OnDestroy {
    formActive: boolean = true;


    restaurantForm = new FormGroup( {
        .........
        .........

    });

    constructor(public restaurantService: RestaurantService) { }

    onSubmit() {
        let value = this.restaurantForm.value;

        ............
        ............
        ............

        this.restaurantService.addRestaurant(this.restaurant)
        .subscribe(
            res =>{ this.result = res,
                    console.log(this.result)},
            error=> {this.error = error.
                    console.log(this.error)}
        )
    }


    ngOnInit() { 
        for (let i=0; i<24; i++) { 
            if( i === 0) {
               this.timesHour.push(0 +''+i); 
            }
            else if ((Math.log10(i)+1) < 2 ) {
                this.timesHour.push(0 +''+i);
            } else {
                this.timesHour.push(String(i));
            }
        }
        for (let i=0; i<60; i++) {
            if( i === 0) {
               this.timesMin.push(0 +''+i); 
            }
            else if ((Math.log10(i)+1) < 2 ) {
                this.timesMin.push(0 +''+i);
            } else {
                this.timesMin.push(String(i));
            }
        }
    }

    ngOnDestroy() {}

}

This is the error message I am receiving:

EXCEPTION: Error: Uncaught (in promise): Can't resolve all parameters for RestaurantFormComponent: (?).
EXCEPTION: Error: Uncaught (in promise): Can't resolve all parameters for RestaurantFormComponent: (?).
STACKTRACE:
Error: Uncaught (in promise): Can't resolve all parameters for RestaurantFormComponent: (?).
    at resolvePromise (zone.js?1467669664341:538)
    at zone.js?1467669664341:515
    at ZoneDelegate.invoke (zone.js?1467669664341:323)
    at Object.onInvoke (core.umd.js:9100)
    at ZoneDelegate.invoke (zone.js?1467669664341:322)
    at Zone.run (zone.js?1467669664341:216)
    at zone.js?1467669664341:571
    at ZoneDelegate.invokeTask (zone.js?1467669664341:356)
    at Object.onInvokeTask (core.umd.js:9091)
    at ZoneDelegate.invokeTask (zone.js?1467669664341:355)
Unhandled Promise rejection: Can't resolve all parameters for RestaurantFormComponent: (?). ; Zone: angular ; Task: Promise.then ; Value: BaseException$1 {message: "Can't resolve all parameters for RestaurantFormComponent: (?).", stack: "Error: Can't resolve all parameters for Restaurant…ngular/compiler/bundles/compiler.umd.js:14640:81)"}
Error: Uncaught (in promise): Can't resolve all parameters for    RestaurantFormComponent: (?).(…)

Answer №1

I encountered a similar issue with Angular 2 rc4, but I was able to resolve it by importing and using Inject. Below is a snippet of the code that fixed the problem:

import { Injectable,Inject } from '@angular/core';
...


@Injectable() 
export class RestaurantService {
   constructor(@Inject(Http) private _http: Http) {
...
}

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

What is the method for obtaining the return type based on the type of a generic function?

Within my api function, I utilize a parser function that is generic and typically returns the same type as its input. However, in some cases, this may be different for simplification purposes. When using the api function, I am able to determine the type t ...

Angular: Do Modules or Components Represent Pages in an Application?

Is it better to have a separate module for each page or a separate component for each page? What are the benefits of using one module for an entire site and loading different components for page transitions? ...

Organizing JSON keys based on their values using Typescript

In the context of a main JSON structure represented below, I am interested in creating two separate JSONs based on the ID and Hobby values. x = [ {id: "1", hobby: "videogames"}, {id: "1", hobby: "chess"}, {id: "2", hobby: "chess ...

Start Angular application using SSL encryption

I am striving to launch my Angular (7+) project with an SSL certificate on localhost (https://localhost:4200). Following the guidance provided in this source - Get angular-cli to ng serve over HTTPS, I attempted the following steps: 1) angular.json { " ...

I'm encountering a 404 error on Next.js localhost:3000

Embarking on a fresh project in Next.js, my folder structure looks like this: https://i.stack.imgur.com/HhiJo.png However, upon navigating to localhost:3000, I am greeted with a 404 error screen. It seems there is an issue with the routing, but unfortuna ...

The improved approach to implementing guards in Angular

I am currently looking for the most effective way to utilize Angular "guards" to determine if a user is logged in. Currently, I am checking if the token is stored. However, I am wondering if it would be better to create an endpoint in my API that can verif ...

Is it possible to combine two separate host listeners into a single function in Angular 2?

One solution is to combine 2 different host listeners into a single function so that it can be called whenever needed. @HostListener('window:unload', ['$event']) unloadHandler() { this.eventService.send({ name: 'onUnload' }) ...

Unveiling the proper extension of component props to default HTML button props

Currently, I am in the process of developing a button component that includes a variant prop to specify its color scheme. Below is a simplified version of the code: interface Props extends React.HTMLProps<HTMLButtonElement> { variant: 'yellow ...

Do I really need to install @angular/router as a dependency in Angular CLI even if I don't plan on using it?

After creating a new Angular CLI project, I noticed that certain dependencies in the package.json file seemed unnecessary. I wanted to remove them along with FormModules and HttpModules from imports: @angular/forms": "^4.0.0", @angular/http": "^4.0.0", @a ...

Unable to perform module augmentation in TypeScript

Following the guidelines provided, I successfully added proper typings to my react-i18next setup. The instructions can be found at: However, upon creating the react-i18next.d.ts file, I encountered errors concerning unexported members within the react-i18 ...

How can an additional value be sent to the form validation method?

I have created a form group like this: import { checkPasswordStrength } from './validators'; @Component({ .... export class PasswordComponent { ... this.userFormPassword = this.fb.group({ 'password': ['', [ ...

The type 'Promise<any>' cannot be assigned to the type 'Contact[]'

After exhausting all my resources on the internet and StackOverflow, I still couldn't find the right answer. This is my first project in Angular with MongoDB, but I keep encountering this error: "Type 'Promise' is not assignable to type &apo ...

What is the best way to show summary calculations in the footer of a PrimeNG table?

I'm struggling to figure out how to create a summary function at the end of a PrimeNG p-table. I need to be able to calculate totals or minimum values for specific columns in the table based on the visible rows. My initial attempt involved trying to ...

Error message displaying Angular Service not able to be injected into component: StaticInjectorError in AppModule

I'm currently attempting to inject a SpotifyService service into a SearchComponent component, where the service requires Http as a parameter. Below is my module setup: @NgModule({ imports: [ BrowserModule, FormsModule, RouterModule ], decla ...

Can someone please provide guidance on how I can access the current view of a Kendo Scheduler when switching between views, such as day view or week

<kendo-scheduler [kendoSchedulerBinding]="events" [selectedDate]="selectedDate" [group]="group" [resources]="resources" style="height: 600px;" [workDayStart]="workDayStart" [workDayEnd] ...

Is there a method to ensure the strong typing of sagas for dispatching actions?

Within redux-thunk, we have the ability to specify the type of actions that can be dispatched enum MoviesTypes { ADD_MOVIES = 'ADD_MOVIES', } interface AddMoviesAction { type: typeof MoviesTypes.ADD_MOVIES; movies: MovieShowcase[]; } typ ...

The TypeScript error ts2322 occurs when using a generic constraint that involves keyof T and a

Trying to create a generic class that holds a pair of special pointers to keys of a generic type. Check out an example in this playground demo. const _idKey = Symbol('_idKey') const _sortKey = Symbol('_sortKey') export interface BaseSt ...

Angular web application can retrieve JSON data from a web API controller, allowing for

I'm currently utilizing ASP.NET Core on the backend and Angular on the frontend. My API delivers data in JSON format from the backend. I've set up a service to fetch the API data, but it's returning 'undefined' at the moment. emp ...

Sorting elements in an array based on an 'in' condition in TypeScript

I am currently working with an arrayList that contains employee information such as employeename, grade, and designation. In my view, I have a multiselect component that returns an array of grades like [1,2,3] once we select grade1, grade2, grade3 from the ...

Using Material-UI with TypeScript

Attempting to integrate TypeScript/React with Material UI has been quite the challenge for me so far. Here is my index.tsx file: declare function require(p: string): any; var injectTapEventPlugin = require("react-tap-event-plugin"); injectTapEventPlugin( ...