Angular 2 Service Error - No provider for Http - angularjs

I'm currently receiving the following error:
EXCEPTION: No provider for Http! (Login -> AuthHttp -> Http)
AuthHttp is a reference to Angular2-jwt. Could this be an issue with that? I've been staring at this for a while, and I can't find what error I could possibly have.
In my login.ts:
import {Component} from 'angular2/core';
import {
FORM_DIRECTIVES,
FormBuilder,
ControlGroup,
Validators,
AbstractControl,
Control
} from 'angular2/common';
import {Http, Headers} from 'angular2/http';
import {Router} from 'angular2/router';
import {ButtonRadio} from 'ng2-bootstrap/ng2-bootstrap';
import {AuthHttp, AuthConfig} from 'angular2-jwt';
import {AuthService} from '../../services/auth/authService';
import {AlertService} from '../../services/alerts/alertsService';
import {User} from '../../datatypes/user/user';
#Component({
selector: 'login',
template: require('./login.html'),
directives: [ ButtonRadio, FORM_DIRECTIVES ],
providers: [AuthService, AlertService, Http, AuthHttp]
})
In my main.ts:
document.addEventListener('DOMContentLoaded', function main() {
bootstrap(App, [
('production' === process.env.ENV ? [] : ELEMENT_PROBE_PROVIDERS),
HTTP_PROVIDERS,
ROUTER_PROVIDERS,
provide(LocationStrategy, { useClass: HashLocationStrategy }),
provide(AuthConfig, { useFactory: () => {
return new AuthConfig({
headerName: 'Authorization',
//headerPrefix: 'Bearer ',
tokenName: 'auth_token',
noJwtError: true
});
}}),
AuthHttp,
Http,
ConnectionBackend
])
.catch(err => console.error(err));
});

You have to add HTTP_BINDINGS
import {HTTP_BINDINGS} from 'angular2/http';
bootstrap(..., [
...
HTTP_BINDINGS,
...
]).catch(...);

It seems that this was indeed an error with Angular2-jwt, or at least with its configuration. Here is the way it should be configured.
Still, I've managed to clean things up a bit. If this problem actually runs deeper, I'll try to reopen.

Related

$Injector Error on Angular Upgrade from 1.6.6 to 6

I did Angular upgrade from Angular.Js 1.6.6 to Angular 6 using Webpack 4:
import 'core-js/es7/reflect';
import 'zone.js';
import 'reflect-metadata';
import 'rxjs';
import { NgModule } from '#angular/core';
import { FormsModule } from '#angular/forms';
import { Routes, RouterModule } from '#angular/router';
import { BrowserModule } from '#angular/platform-browser';
import { UpgradeModule, downgradeComponent, downgradeInjectable, setAngularJSGlobal } from '#angular/upgrade/static';
import { module } from './app.module.ajs';
import './config/routes';
import AppComponent from './components/app/app';
import Application from './directives/application/application';
import { platformBrowserDynamic } from "#angular/platform-browser-dynamic";
console.log('NgModule');
const appRoutes: Routes = [
];
#NgModule({
declarations: [AppComponent, Application],
entryComponents: [AppComponent],
imports: [
BrowserModule,
FormsModule,
RouterModule.forRoot(appRoutes),
UpgradeModule
]
})
class AppModule {
constructor(public upgrade: UpgradeModule) {
console.log('AppModule constructor');
}
ngDoBootstrap() {
console.log('AppModule ngDoBootstrap');
}
}
console.log('setAngularJSGlobal ...');
setAngularJSGlobal(window['angular']);
console.log('setAngularJSGlobal!!!');
import main = require('./main');
console.log('Before bootstrapModule module.name: ', module.name);
platformBrowserDynamic().bootstrapModule(AppModule).then(platformRef => {
console.log('Hybrid mode: Angular + Angular.Js');
module.directive('appRoot', downgradeComponent({ component: AppComponent }));
const upgrade = platformRef.injector.get(UpgradeModule) as UpgradeModule;
console.log('bootstrapModule: ', module.name);
main['launchAngular']();
upgrade.bootstrap(document.body, [module.name], { strictDi: true });
});
created custom alias, added correct paths to tsconfig, Webpack build pass & produce output, but when application starts in browser, error popups in console: ngRoute is missing or incorrect ng module components
What is not done correctly & how to fix this error?
Fixed some Webpack aliases. Replaced: Angular-Resource with Axios, Angular-Route with UI-Router/Angular-Hybrid, refactored couple controllers to components/directives & services, got rid from $rootScope & Magic happened: Upgrade started to work.

Can't resolve all parameters for Auth: (?) error, ionic2 AngularJS

i wanted to provide authonification to my ionic2 app, so i followed the official documentation and applied it to a brand new ionic2 app ionic start my_app blank
once i serve my app, this error fires :
Error: Can't resolve all parameters for Auth: (?).
at syntaxError (http://localhost:8100/build/main.js:107898:34)
at CompileMetadataResolver._getDependenciesMetadata (http://localhost:8100/build/main.js:121235:35)
at CompileMetadataResolver._getTypeMetadata (http://localhost:8100/build/main.js:121103:26)
at CompileMetadataResolver._getInjectableMetadata (http://localhost:8100/build/main.js:121089:21)
at CompileMetadataResolver.getProviderMetadata (http://localhost:8100/build/main.js:121379:40)
at http://localhost:8100/build/main.js:121308:49
at Array.forEach (<anonymous>)
at CompileMetadataResolver._getProvidersMetadata (http://localhost:8100/build/main.js:121269:19)
at CompileMetadataResolver.getNgModuleMetadata (http://localhost:8100/build/main.js:120924:50)
at JitCompiler._loadModules (http://localhost:8100/build/main.js:131988:66)
i've injected Auth with providers in app.moodule.ts as you can
import { BrowserModule } from '#angular/platform-browser';
import { ErrorHandler, NgModule } from '#angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '#ionic-native/splash-screen';
import { StatusBar } from '#ionic-native/status-bar';
import { MyApp } from './app.component';
import { Auth } from '#ionic/cloud-angular';
#NgModule({
declarations: [
MyApp,
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
],
providers: [
StatusBar,
SplashScreen,
Auth,
{provide: ErrorHandler, useClass: IonicErrorHandler }
]
})
export class AppModule {}
according to my researches, this error comes from:
Having forgot to decorate the Auth class with #Injectable() or #Inject(Auth)
i have tried doing so by injecting :
#IonicPage()
#Component({
selector: 'page-home',
templateUrl: 'home.html',
})
#Injectable()
export class HomePage {........}
OR
export class HomePage {
constructor(#Inject(Auth) public auth: Auth) {
}
.......
}
But this shows the same error though.
Having a dependency in the Auth constructor that i haven't provided in app.module.ts
as you can see, i've handled this case in my code.
A circular dependency.
which i really think is the issue here, honestly i got a clue how to check this out since i still a beginner.
Hope someone can help

Angular 2 Can't resolve all parameters for abcService

Getting the following error message when trying to inject a config object into a service:
Error: Can't resolve all parameters for abcService: (?, [object Object]).
I followed the documentation on dependency injection, but can't get it working.
In my service abc.service.ts I have the following:
import { IabcConfig } from 'abc.types';
export let ABC_CONFIG = new OpaqueToken('abc.config');
#Injectable()
export class abcService {
private config: IabcConfig;
constructor(#Inject(ABC_CONFIG) config: IabcConfig, private http: Http) {
this.config = config;
}
}
and in my module abc.module.ts:
import { NgModule, ModuleWithProviders } from '#angular/core';
import { CommonModule } from '#angular/common';
import { IabcConfig } from '#abc/abc.types';
import { abcService, ABC_CONFIG } from '#abc/abc.service';
export const abcConfig: IabcConfig = {
save: false,
title: 'ABC',
}
#NgModule({
imports: [
CommonModule
]
})
export class ABCModule {
static forRoot(): ModuleWithProviders {
return {
ngModule: SharedModule,
providers: [
o7AuthenticationService,
{ provide: ABC_CONFIG, useValue: abcConfig },
]
};
}
}
Important libs I am using:
angular#2.4.0
angular2-universal#2.1.0-rc.1
zone.js#0.7.4
Add import for Angular's HttpModule in ABCModule.
....
#NgModule({
imports: [
CommonModule,
HttpModule
]
})
...
Update: probably I misunderstood original code, but I still assume that angular cannot find/resolve HTTP that you use in AbcService's constructor. Unless you didn't provide piece of code for that...
So ends up that when using a custom npm package, with services that take injectable objects, at least in webpack.config.ts we had to add our custom package #abc under externals: includeClientPackages(/#angularclass|#angular|#abc)
This fixed all the 'could not resolve parameter' errors

How to achieve date filtering in Angular2

I have a class inside of which I want to use date filtering as it used to be in Angular 1:
$filter('date')(startDate, 'yyyy-MM-dd HH:mm:ss')
Now I want to achieve this using Angular 2. As far as I can see, I could use DatePipe class. But the problem is that I don't know how to import it inside of my class file:
import { Injectable } from '#angular/core'
import { Http, Response, Headers } from '#angular/http';
import { InputValidatorService } from './input-validator.service';
import { Pipe, PipeTransform } from '#angular/core';
...
myFunctionInsideOfAClass(){
var datePipe = new DatePipe(); // Symbol 'DatePipe' can not be properly resolved, probably it is located in inaccessible module.
}
How can I achieve this?
EDIT: My app module:
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule } from '#angular/forms';
..
#NgModule({
imports: [BrowserModule, FormsModule, HttpModule],
declarations: [AppComponent, MapComponent, AtileLayerDirective, MapDirective, mapControlDirective, ToolsComponent, SearchComponent],
bootstrap: [AppComponent],
providers: [{
provide: Http,
useFactory: (_backend: ConnectionBackend, _defaultOptions: RequestOptions) => new HttpInterceptor(_backend, _defaultOptions),
deps: [XHRBackend, RequestOptions]
}, mapManager, SearchService, StatusIconProvider
]
})
import {DatePipe} from '#angular/common';
#NgModule({
...
providers: [ /* other providers */, DatePipe],
...
})

Angular 2.0 Routing Issue

In my main.ts the code is like this.
import {provide, enableProdMode} from 'angular2/core';
import {bootstrap} from 'angular2/platform/browser';
import {ROUTER_PROVIDERS} from 'angular2/router';
import {HTTP_PROVIDERS} from 'angular2/http';
import {APP_BASE_HREF} from 'angular2/platform/common';
import {AppComponent} from './app/components/app.component';
enableProdMode();
bootstrap(AppComponent, [
ROUTER_PROVIDERS, HTTP_PROVIDERS,
provide(APP_BASE_HREF, { useValue: '<%= APP_BASE %>' })
]);
In my app.component.ts file I have the follwing code.
import {Component} from 'angular2/core';
import {enableProdMode} from 'angular2/core';
import {Router, ROUTER_DIRECTIVES, ROUTER_PROVIDERS, RouteConfig, RouteParams} from 'angular2/router';
import {SportsLiveFeedService} from '../shared/index';
import {MainComponent} from '../main/index';
import {ResultsComponent} from '../results/index';
#Component({
selector: 'sd-app',
viewProviders: [SportsLiveFeedService],
templateUrl: 'app/components/app.component.html',
styleUrls: ['css/bootstrap.min.css', 'css/main.css'],
directives: [ROUTER_DIRECTIVES]
})
#RouteConfig([
{
path: '/',
name: 'Main',
component: MainComponent
},
{
path: '/results/:id',
name: 'Results',
component: ResultsComponent
}
])
export class AppComponent {
constructor(private router: Router) {}
}
And in the ResultsComponent my code is like this.
import {Component} from 'angular2/core';
import {Inject} from 'angular2/di';
import {CORE_DIRECTIVES, FORM_DIRECTIVES} from 'angular2/common';
import {SportsLiveFeedService} from '../../shared/index';
#Component({
selector: 'sd-about',
templateUrl: 'app/results/components/results.component.html',
styleUrls: ['css/bootstrap.min.css', 'css/main.css'],
directives: [FORM_DIRECTIVES, CORE_DIRECTIVES],
providers: [SportsLiveFeedService]
})
export class ResultsComponent implements OnInit {
eventsDetails: [];
constructor(private _sportsLiveFeedService: SportsLiveFeedService){
this._sportsLiveFeedService = _sportsLiveFeedService;
}
ngOnInit(){
this._sportsLiveFeedService
.getEachEventInDetailByMeetingId()
.subscribe(p => this.eventsDetails = p)
}
}
The issue is when I first screen is loading just fine. But when I navigate to http://localhost:5555/results/121212 like this, The second screen UI is not showing. Please help me to fix this issue. I am new to Angular 2.0

Resources