I use a service in an Angular 2 app, and I get an error which is attached below.
I started this project using "Angular 2 QuickStart" cloned as 'my-proj'.
Error screenshot
systemjs.config.js
/**
* System configuration for Angular samples
* Adjust as necessary for your application needs.
*/
(function (global) {
System.config({
paths: {
// paths serve as alias
'npm:': 'node_modules/'
},
// map tells the System loader where to look for things
map: {
// our app is within the app folder
app: 'app',
// angular bundles
'#angular/core': 'npm:#angular/core/bundles/core.umd.js',
'#angular/common': 'npm:#angular/common/bundles/common.umd.js',
'#angular/compiler': 'npm:#angular/compiler/bundles/compiler.umd.js',
'#angular/platform-browser': 'npm:#angular/platform-browser/bundles/platform-browser.umd.js',
'#angular/platform-browser-dynamic': 'npm:#angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
'#angular/http': 'npm:#angular/http/bundles/http.umd.js',
'#angular/router': 'npm:#angular/router/bundles/router.umd.js',
'#angular/forms': 'npm:#angular/forms/bundles/forms.umd.js',
'#angular/upgrade': 'npm:#angular/upgrade/bundles/upgrade.umd.js',
// other libraries
'rxjs': 'npm:rxjs',
'angular-in-memory-web-api': 'npm:angular-in-memory-web-api',
},
// packages tells the System loader how to load when no filename and/or no extension
packages: {
app: {
main: './main.js',
defaultExtension: 'js'
},
rxjs: {
defaultExtension: 'js'
},
'angular-in-memory-web-api': {
main: './index.js',
defaultExtension: 'js'
}
}
});
})(this);
app.module.ts
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { HttpModule, JsonpModule } from '#angular/http';
import { AppComponent } from './app.component';
import { ProfileComponent } from './components/profile.component';
#NgModule({
imports: [ BrowserModule,HttpModule,JsonpModule ],
declarations: [ AppComponent,ProfileComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
profile.component.ts
import { Component } from '#angular/core';
import {GithubService} from '../services/github.service';
import 'rxjs/add/operator/map';
#Component({
moduleId:module.id,
selector: 'profile',
templateUrl:'profile.component.html'
})
export class ProfileComponent {
constructor(private githubService:GithubService){
this.githubService.getUser().subscribe(user => {
console.log(user);
});
}
}
github.service.ts
import { Injectable } from '#angular/core';
import {Http,Headers} from '#angular/Http';
import 'rxjs/add/operator/map';
#Injectable()
export class GithubService{
private username:string;
constructor(private http:Http){
console.log('Github Service Ready...');
this.username='bradtraversy';
}
getUser(){
return this.http.get('http://api.github.com/users'+this.username).map(res => res.json);
}
}
In github.service.ts, change
import {Http,Headers} from '#angular/Http'
to
import {Http,Headers} from '#angular/http'
might help.
Related
I am trying to implement login with google in asp.net core 5 and AngularJs. After reading some tutorials on this, I have found this package. So I have installed it via npm:
npm i angularx-social-login
Then did nessesary imports:
import { SocialLoginModule, SocialAuthServiceConfig } from 'angularx-social-login';
import { GoogleLoginProvider } from 'angularx-social-login';
And then configured the providers:
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: AuthorizeInterceptor, multi: true },
{
provide: 'SocialAuthServiceConfig',
useValue: {
autoLogin: false,
providers: [
{
id: GoogleLoginProvider.PROVIDER_ID,
provider: new GoogleLoginProvider(
'883654869277-m2mlgsroh8vsmt0tg82lmo4cnt0cuqs3.apps.googleusercontent.com'
)
},
],
} as SocialAuthServiceConfig
},
],
But then I run the application, I am getting this error:
Microsoft.AspNetCore.SpaServices: Error: (node:13652) [DEP0111] DeprecationWarning: Access to process.binding('http_parser') is deprecated.
Microsoft.AspNetCore.SpaServices: Error: (Use `node --trace-deprecation ...` to show where the warning was created)
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { FormsModule } from '#angular/forms';
import { HttpClientModule, HTTP_INTERCEPTORS } from '#angular/common/http';
import { RouterModule } from '#angular/router';
import { AppComponent } from './app.component';
import { NavMenuComponent } from './nav-menu/nav-menu.component';
import { HomeComponent } from './home/home.component';
import { CounterComponent } from './counter/counter.component';
import { FetchDataComponent } from './fetch-data/fetch-data.component';
import { ApiAuthorizationModule } from 'src/api-authorization/api-authorization.module';
import { AuthorizeGuard } from 'src/api-authorization/authorize.guard';
import { AuthorizeInterceptor } from 'src/api-authorization/authorize.interceptor';
import { SocialLoginModule, SocialAuthServiceConfig } from 'angularx-social-login'; import { GoogleLoginProvider } from 'angularx-social-login';
//config gauth
//end gauth
#NgModule({
declarations: [
AppComponent,
NavMenuComponent,
HomeComponent,
CounterComponent,
FetchDataComponent
],
imports: [
BrowserModule.withServerTransition({ appId: 'ng-cli-universal' }),
HttpClientModule,
FormsModule,
SocialLoginModule,
ApiAuthorizationModule,
RouterModule.forRoot([
{ path: '', component: HomeComponent, pathMatch: 'full' },
{ path: 'counter', component: CounterComponent },
{ path: 'fetch-data', component: FetchDataComponent, canActivate: [AuthorizeGuard] },
])
],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: AuthorizeInterceptor,
multi: true
},
{
provide: 'SocialAuthServiceConfig',
useValue: {
autoLogin: false,
providers: [
{
id: GoogleLoginProvider.PROVIDER_ID,
provider: new GoogleLoginProvider(
'883654869277-m2mlgsroh8vsmt0tg82lmo4cnt0cuqs3.apps.googleusercontent.com'
)
},
],
} as SocialAuthServiceConfig
}
],
bootstrap: [AppComponent]
})
export class AppModule { }
What can I do to make it work?
angularx-social-login is no longer being maintained and deprecated.
If you check out their npm documentation they recommend moving to #abacritt/angularx-social-login.
ref: https://www.npmjs.com/package/angularx-social-login
Might help you out to git rid of depreciation warnings/errors.
Runtime Error
Cannot find module "angularfire2/database"
Stack
Error: Cannot find module "angularfire2/database"
Home.Ts
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { FirebaseProvider } from './../../providers/firebase/firebase';
//error
import { FirebaseListObservable } from 'angularfire2/database';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
shoppingItems: FirebaseListObservable<any[]>;
newItem = '';
constructor(public navCtrl: NavController, public firebaseProvider: FirebaseProvider) {
this.shoppingItems = this.firebaseProvider.getShoppingItems();
}
addItem() {
this.firebaseProvider.addItem(this.newItem);
}
removeItem(id) {
this.firebaseProvider.removeItem(id);
}
}
The error is in this line
import { FirebaseListObservable } from 'angularfire2/database';
app.module.Ts
import { BrowserModule } from '#angular/platform-browser';
import { ErrorHandler, NgModule } from '#angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { ListPage } from '../pages/list/list';
import { StatusBar } from '#ionic-native/status-bar';
import { SplashScreen } from '#ionic-native/splash-screen';
import { HttpModule } from '#angular/http';
import { AngularFireDatabaseModule } from 'angularfire2/database';
import { AngularFireModule } from 'angularfire2';
import { FirebaseProvider } from '../providers/firebase/firebase';
const firebaseConfig = {
apiKey: "$$$$$$$$$",
authDomain: "44444444.firebaseapp.com",
databaseURL: "https://44444.firebaseio.com",
projectId: "44444",
storageBucket: "i4444[enter image description here] [1]3.appspot.com",
messagingSenderId: "************"
};
#NgModule({
declarations: [
MyApp,
HomePage,
ListPage
],
imports: [
BrowserModule,
HttpModule,
AngularFireDatabaseModule,
AngularFireModule.initializeApp(firebaseConfig),
IonicModule.forRoot(MyApp),
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
HomePage,
ListPage
],
providers: [
StatusBar,
SplashScreen,
{provide: ErrorHandler, useClass: IonicErrorHandler},
FirebaseProvider
]
})
export class AppModule {}'
output:
Runtime Error
Cannot find module "angularfire2/database"
Stack
Error: Cannot find module "angularfire2/database"at Object.195 (http://localhost:8100/build/main.js:89:7)at webpack_require (http://localhost:8100/build/vendor.js:55:30)at Object.194 (http://localhost:8100/build/main.js:44:87)
try
import { AngularFireList } from 'angularfire2/database';
instead of
import { FirebaseListObservable } from 'angularfire2/database';
Which version do you use? In AngularFire 5.0 FirebaseListObservable is removed
I am running hybrid angular 1 app and angular 2 app. I have created a component ActivateAccount. While i am running this application.
I am getting console error while downgrading component. Cannot read property 'resolveComponentFactory' of undefined <activate-account class="ng-scope">
I do searched related to this error but i found nothing.
I am referring Using Angular Components from AngularJS Code
app.module.js
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { UpgradeModule, downgradeComponent } from '#angular/upgrade/static';
import { HttpModule } from '#angular/http';
import { ActivateAccountComponent } from '/thinkshop/widgets2/thinkshopapplication/activateaccount/activateaccount.ts';
#NgModule({
imports: [
BrowserModule,
UpgradeModule ,
HttpModule
],
declarations: [
ActivateAccountComponent
],
entryComponents: [
ActivateAccountComponent
]
})
export class AppModule {
constructor(private upgrade: UpgradeModule) { }
ngDoBootstrap() {
var app= angular.module('IdeolveActivateAccount', ['ngMaterial', 'jlareau.bowser', 'validation.match', 'ngDialog', 'ngMessages']);
app.controller("ActivateAccountApp", loadActivateAccountApp);
angular.module('IdeolveActivateAccount').directive('activateAccount', downgradeComponent({ component: ActivateAccountComponent }));
app.component("ideolveformcomponent",{
bindings:{
showideolvelink: '<'
},
controller: 'ActivateAccountApp',
templateUrl: '/thinkshop/widgets2/thinkshopapplication/login/template/landingdisplay.html'
});
this.upgrade.bootstrap(document.body, ['IdeolveActivateAccount']);
}
}
activateaccount.ts
import { Component } from '#angular/core';
#Component({
selector: 'activate-account',
template: '<div class="ActivateAccountContainer marginlefttwentypx margintoptwentypx marginrighttwentypx marginbottomtwentypx heighthundredpercent"></div>'
})
export class ActivateAccountComponent {
constructor() {}
}
I think i am missing something. I have checked all my code against tutorial given into above link, But i am getting console error.
After a long discussion, the following steps helped:
app.module.ts
providers: [
{provide: 'CLIENT_ID', useValue: CLIENT_ID},
{provide: 'APP_NAME', useValue: APP_NAME},
{provide: 'AUTH_TOKEN', useValue: AUTH_TOKEN},
{provide: 'CAN_EDIT', useValue: CAN_EDIT},
//{provide: Http, useValue: Http}, <-- unneccesary, when import HttpModule
ActivateAccountService // <-- provide service in module, not component
]
activate-account.service.ts
Removing URLSearchParams from constructor, bacause it is not injectable object. Instead of this, you shoul use #angular/router module
I'm trying to upgrade an angularjs directive to use it my angular component. I've gotten the hybrid (ng1 + ng2) environment to work. I can also inject angularjs services in angular and use them in angular components (I actually got this working even with angularjs 1.4.x).
Now I'm trying to use an existing angularjs directive in angular, but not working.
For reference, are some snippets of my codes.
[index.html] (my-app is the Angular 4 root component)
...
<body>
<div class="banner">Angular Migration</div>
<my-app>Loading...</my-app>
...
</body>
...
[main.ts] (bootstrapping code)
import { platformBrowserDynamic } from '#angular/platform-browser-dynamic';
import { UpgradeModule } from '#angular/upgrade/static';
import { Router } from '#angular/router';
import { AppModule } from './app.module';
platformBrowserDynamic().bootstrapModule(AppModule).then(platformRef => {
let upgrade = platformRef.injector.get(UpgradeModule) as UpgradeModule;
upgrade.bootstrap(document.documentElement, ['sampleApp']);
platformRef.injector.get(Router).initialNavigation();
});
[app.module.ts] (Angular 4 module)
import { NgModule, Component } from '#angular/core';
import { HashLocationStrategy, LocationStrategy, CommonModule } from '#angular/common';
import { BrowserModule } from '#angular/platform-browser';
import { UpgradeModule } from '#angular/upgrade/static';
import { RouterModule, Routes, UrlHandlingStrategy } from '#angular/router';
import { HybridUrlHandlingStrategy } from './hybridUrlHandlingStrategy';
import { AppComponent } from './app.component';
export const routes: Routes = [
...
];
#NgModule({
imports: [
CommonModule,
BrowserModule,
UpgradeModule,
RouterModule.forRoot([], { useHash: true, initialNavigation: false })
],
providers: [
{ provide: LocationStrategy, useClass: HashLocationStrategy },
{ provide: UrlHandlingStrategy, useClass: HybridUrlHandlingStrategy },
{ provide: 'appService', useFactory: (i: any) => i.get('appService'), deps: ['$injector'] },
{ provide: 'mdToHtml', useFactory: (i: any) => i.get('mdToHtml'), deps: ['$injector'] }
],
declarations: [
AppComponent
],
bootstrap: [ AppComponent ]
})
export class AppModule {
ngDoBootstrap() { }
}
[app.component.ts] (Angular 4 component)
import { Component } from '#angular/core';
#Component({
selector: 'my-app',
template: `
<router-outlet></router-outlet>
<div ng-view></div>
`,
})
export class AppComponent { }
[app.js] (AngularJs app)
'use strict';
angular.module('sampleApp', [
'ngRoute',
'app.components.services.appService'
])
.config(function ($routeProvider) {
$routeProvider
.otherwise({
template: ''
});
});
[myStars.js] (AngularJs directive)
'use strict';
angular.module('app.components.directives.myStars', [])
.controller('MyStarsCtrl', function() {
console.log("**** in MyStarsCtrl ")
})
.component('myStars', {
restrict: 'E',
bindings: {
count: '=count'
},
template: '<div>***** M Y S T A R S *****</div>'
});
[myStars.ts] (an attempt to migrate myStars directive to Angular 4)
import { Directive, ElementRef, Injector, Input, Output, EventEmitter } from '#angular/core';
import { UpgradeComponent } from '#angular/upgrade/static';
#Directive({
selector: 'my-stars'
})
export class MyStarsDirective extends UpgradeComponent {
#Input() count: number;
#Output() clicked: EventEmitter<number>;
constructor(elementRef: ElementRef, injector: Injector) {
super('myStars', elementRef, injector);
}
}
[test.module.ts] (Angular 4 test module)
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { RouterModule, Routes} from '#angular/router';
import { TestComponent } from './test.component';
// importing the new MyStarsDirective)
import { MyStarsDirective } from '../../../components/directives/myStars/myStars';
const thisRoute: Routes = [
{
path: 'test/:id',
component: TestComponent
}
];
#NgModule({
declarations: [
TestComponent,
MyStarsDirective, // <<<< adding directive here
],
providers: [],
imports: [
CommonModule,
RouterModule.forChild(thisRoute)
],
exports: [
RouterModule
]
})
export class TestModule {}
[test.component.ts] (Angular 4 test component)
import { Component, Inject, OnInit } from '#angular/core';
import { ActivatedRoute } from '#angular/router';
import { FormsModule } from '#angular/forms';
import { HybridUrlHandlingStrategy } from '../../../hybridUrlHandlingStrategy';
import { MyStarsDirective } from '../../../components/directives/myStars/myStars';
#Component({
templateUrl: './test.component.html'
})
export class TestComponent implements OnInit {
routeParams: any
myService: any
mdToHtml: any
constructor(
#Inject('myService') myService: any,
#Inject('mdToHtml') mdToHtml: (str: string) => string,
private activatedRoute: ActivatedRoute
) {
this.myService = myService;
this.mdToHtml = mdToHtml;
}
ngOnInit() {
this.routeParams = this.activatedRoute.params.subscribe(params => {
console.log("params", params['groupId'])
...
}
ngOnDestroy() {
this.routeParams.unsubscribe();
}
}
[test.component.html] (Angular 4 html)
...
<my-stars></my-stars> <!-- <<<< using directive here -->
...
Note: I've also upgrade angularjs version to 1.5 just to make this hybrid app works.
Here's the error when I browser the test component page:
Any help would be greatly appreciated.
Thanks.
For anyone interested, here's the solution to this error.
[test.module.ts] (Angular 4 test module)
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { RouterModule, Routes} from '#angular/router';
import { TestComponent } from './test.component';
// importing the new MyStarsDirective)
import { MyStarsDirective } from '../../../components/directives/myStars/myStars';
const thisRoute: Routes = [
{
path: 'test/:id',
component: TestComponent
}
];
#NgModule({
declarations: [
TestComponent,
MyStarsDirective, // <<<< adding directive here
],
providers: [
{
provide: '$scope',
useFactory: i => i.get('$rootScope'),
deps: ['$injector']
}, // <<<< added this section to fix the No provider for $scope error
],
imports: [
CommonModule,
RouterModule.forChild(thisRoute)
],
exports: [
RouterModule
]
})
export class TestModule {}
I found the answer in this link https://github.com/angular/angular/issues/14993 (inspired by BrunoPoeta)
See comment by gkalpak on March 10.
Now let's see if I can upgrade a regular directive and use 1.4.x.
I have an Angular 2 project with components that we bring on build into another project written in angular 1. The problem is the files are like 3rd party, we don't want any one to commit them only use them. The files are enter the "target" folder, but in App.Module.ts I can't set import to that folder. Any idea how to do that correctly?
What I don't understnad is how we can use componenet that written somewhere else if we must declare it in 'app.module.ts' files in order to use it in the project.
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { UpgradeModule } from '#angular/upgrade/static';
import { FormsModule } from '#angular/forms';
import { HttpModule } from '#angular/http';
/* HelloWorldComponent is a 3th party, its files are inside target folder,
so how to import it? */
/* import { HelloWorldComponent } from './app/hello-world.component';*/
#NgModule({
declarations: [
HelloWorldComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
UpgradeModule
],
exports: [
HelloWorldComponent
],
entryComponents: [
HelloWorldComponent
],
bootstrap: []
})
export class AppModule {
ngDoBootstrap() {}
}
import { platformBrowserDynamic } from '#angular/platform-browser-dynamic';
platformBrowserDynamic().bootstrapModule(AppModule).then(platformRef => {
const upgrade = platformRef.injector.get(UpgradeModule) as UpgradeModule;
upgrade.bootstrap(document.body, ['myApp']);
;})
import * as _angular_ from 'angular';
declare global {
const angular: typeof _angular_;
}
import { downgradeComponent } from '#angular/upgrade/static';
angular.module('myApp')
.directive(
'helloWorld',
downgradeComponent({component: HelloWorldComponent}) as angular.IDirectiveFactory
);