getting error `Property 'initializeData' does not exist on type of AppConfig` on `useFactory` - angular7

I am fetching data from service on APP_INITIALIZER, but getting error as
Property 'initializeData' does not exist on type of AppConfig
don't know what is the exact issue here. any one help me?
here is my module file:
import { AppConfig } from "./shared-components/auth/AdalService";
import { AppComponent } from './app.component';
import { RoutesModule } from './routes/routes.module';
import { SignInComponent } from './shared-components/user/sign-in/sign-in.component';
export function initializeApp() {
return () => AppConfig.initializeData(); //getting error here
}
#NgModule({
declarations: [
AppComponent,
SignInComponent
],
imports: [
BrowserModule,
AngularFontAwesomeModule,
MsAdalAngular6Module,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: (createTranslateLoader),
deps: [HttpClient]
},
isolate: true
}),
SharedModule,
HttpClientModule,
iboCalendarModule,
RoutesModule,
// HttpClientInMemoryWebApiModule.forRoot(EventData),
StoreModule.forRoot({}),
EffectsModule.forRoot([]),
StoreDevtoolsModule.instrument({
name:'IBO App',
maxAge:25
})
],
providers: [
{
provide: APP_INITIALIZER,
useFactory: initializeApp,
multi: true,
deps: [AppConfig, SignInComponent ]
},
MsAdalAngular6Service,
{
provide: 'adalConfig',
useFactory: getAdalConfig,
deps: []
},
{
provide: HTTP_INTERCEPTORS,
useClass: InsertAuthTokenInterceptor,
multi: true
}
],
bootstrap: [AppComponent]
})
export class AppModule { }
Here is my service.ts:
import { Injectable, OnInit } from '#angular/core';
import { ShareOption } from "./../user/sign-in/sign-in.component";
import { Store, select } from '#ngrx/store';
import { StateShared } from "./../models/models";
#Injectable({
providedIn: 'root'
})
export class AppConfig {
constructor(){}
initializeData() {
return new Promise((resolve, reject) => resolve(true));
}
}

I bought the service in parameter, got issue fixed. my updated chunk is:
export function initializeApp(service:AppConfig) { //getting service object in param
return () => service.initializeData();
}

Related

Angular 12. Inject service via forRoot into an external library, loaded from a module which has been lazy loaded by Compiler

I've created a library with a directive that injects a service. This library is loaded with a forRoot method in each lazy loaded component where is going to be used.
*** library.module ***
export const SERVICE_INYECTION_TOKEN: InjectionToken<any> = new InjectionToken('service')
export interface IDirectiveModuleConfig {
serviceAdapterConfiguration?: {provider: Provider, moduleName: string};
}
#NgModule({
imports: [
CommonModule
],
declarations: [DirectiveDirective],
exports: [DirectiveDirective]
})
export class LibraryModule {
public static forRoot(config: IDirectiveModuleConfig = {}): ModuleWithProviders<LibraryModule> {
console.log("Library loaded in module " + config.serviceAdapterConfiguration.moduleName)
return {
ngModule: LibraryModule,
providers: [
config.serviceAdapterConfiguration.provider
]
};
}
}
*** directive.directive ***
#Directive({
selector: '[directive]',
})
export class DirectiveDirective implements AfterViewInit {
#Input() methodName: string;
constructor(
private element: ElementRef,
private renderer: Renderer2,
#Inject(SERVICE_INYECTION_TOKEN) private service: any
) {}
ngAfterViewInit(): void {
this.element.nativeElement.innerText += this.service[this.methodName]()
this.renderer.setValue(this.element.nativeElement, this.service[this.methodName]())
}
}
In my main project, I have two lazy-loadeds modules, and each one have a component. One of this modules and its component are lazylodaded by the RouterModules. It works OK
*** app-routing.module ***
const routes: Routes = [
{
path: 'a',
loadChildren: () =>
import('./modules/module-a/module-a.module').then((m) => m.ModuleAModule),
},
{
path: 'b',
loadChildren: () =>
import('./modules/module-b/module-b.module').then((m) => m.ModuleBModule),
},
];
#NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
})
export class AppRoutingModule {}
The other one is created by compileModuleAndAllComponentsAsync() and viewContainerRef.createComponent() in the parent component. It works ok without the service inection, but when I inject the service I get a NullInjectorError.
*** app.component ***
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
#ViewChild("viewContainerRef", { read: ViewContainerRef }) viewContainerRef: ViewContainerRef
component = null;
title = 'component-overview';
constructor(private compiler: Compiler, private injector: Injector) {}
async createModuleAndComponetC() {
const componentInjector: Injector = Injector.create({providers:[{provide:'service', useExisting: ServiceCService}]})
this.viewContainerRef.clear()
const module = (await import('./modules/module-c/module-c.module'))
.ModuleCModule;
this.compiler.compileModuleAndAllComponentsAsync(module).then((factory) => {
factory.ngModuleFactory.create(this.injector);
const componentFactory = factory.componentFactories[0]
const component: ComponentRef<any> = this.viewContainerRef.createComponent(componentFactory);
});
}
}
MODULE A (lazy loaded by routerModule working OK) with its component and service
const serviceConfig: IDirectiveModuleConfig = {
serviceAdapterConfiguration: {
provider: { provide: SERVICE_INYECTION_TOKEN, useClass: ServiceAService },
moduleName: 'A',
}
};
#NgModule({
imports: [
LibraryModule.forRoot(serviceConfig),
CommonModule,
ModuleARoutingModuleModule,
],
declarations: [ComponentAComponent],
exports: [ComponentAComponent],
})
export class ModuleAModule {
constructor(){
console.log("moduleA loaded")
}
}
#Component({
selector: 'app-component-a',
templateUrl: './component-a.component.html',
styleUrls: ['./component-a.component.css'],
})
export class ComponentAComponent implements OnInit {
constructor() {}
ngOnInit() {}
}
#Injectable({
providedIn: 'root'
})
export class ServiceAService {
constructor() { }
serviceA(){
return(" service A!")
}
}
MODULE C (loaded manually with compileModuleAndAllComponentsAsync() and viewContainerRef.createComponent()
export const serviceConfig: IDirectiveModuleConfig = {
serviceAdapterConfiguration: {
provider: { provide: SERVICE_INYECTION_TOKEN, useClass: ServiceCService },
moduleName: 'C',
},
};
#NgModule({
imports: [CommonModule, LibraryModule.forRoot(serviceConfig)],
declarations: [ComponentCComponent],
})
export class ModuleCModule {
constructor() {
console.log('moduleC loaded');
}
static
}
#Component({
selector: 'app-component-c',
templateUrl: './component-c.component.html',
styleUrls: ['./component-c.component.css'],
providers: [ServiceCService],
})
export class ComponentCComponent implements OnInit {
constructor() {
console.log('component C constructor');
}
ngOnInit() {
console.log('component C OnInit');
}
}
#Injectable({
providedIn: 'root',
})
export class ServiceCService {
constructor() {}
serviceC() {
return ' service C!';
}
}
In this example Modules A and B are used with router outlet, and module C is loaded with Compiler and the component is used in a *ngCompilerOutlet
I think that the problem is in the way I load my ComponentC... but I'm a little bit lost...
In adition... i've founded that the module C create a new instance each time I load this, and is not working like singleton...
stackblitz with the test project
Finally, I got success!
I saw that I could pass an injector to the viewContainerRef. CreateComponent () method. I tried with the same injector I had used to create the module in the noModuleFactory. Create () method, but it was still wrong.
Finally y realized that NgModule class exports an injector, I suposed this injector provide al the providers in this module and it works ok!!
Now my createModuleAndComponetC() is:
async createModuleAndComponetC() {
this.viewContainerRef.clear();
const module = (await import('./modules/module-c/module-c.module'))
.ModuleCModule;
this.compiler.compileModuleAndAllComponentsAsync(module).then((factory) => {
const module = factory.ngModuleFactory.create(this.injector);
const componentFactory = factory.componentFactories[0];
const component: ComponentRef<any> =
this.viewContainerRef.createComponent(
componentFactory,
0,
module.injector
);
});
}
here is the corrected stackbliz

Issue with Angular library (UMD) and dynamic loading

I have an Angular app that contains a load button. When you click the load button it renders a remote UMD library.
The first time I click the load button I have the following error while importing my library using SystemJS:
core.js:15714 ERROR Error: Uncaught (in promise): TypeError: Cannot read property '__source' of undefined
TypeError: Cannot read property '__source' of undefined
at StaticInjector.push../node_modules/#angular/core/fesm5/core.js.StaticInjector.get (core.js:8984)
when I click a second time, no errors and the library renders correctly.
I narrowed the issue to this statement in my code:
export class PostService {
constructor(private httpClient: HttpClient) { }
If I remove the httpClient service, the library loads correctly but I don't have access to the HttpClient.
If anyone has an idea why my code behaves that way it would be greatly appreciated!
Here is my setup below:
I have the following components im my remote library:
sample-pack-lib.component
|_db2-chart2.component
|_post.service
The library 'samplePack-lib' is compiled with 'ng build samplePack-lib' and I exposed the following output through an express server:
dist/sample-pack-lib/sample-pack-lib.umd.js
db2-chart2.component.ts:
import { Component, ElementRef, ViewChild, AfterViewInit, OnInit } from '#angular/core';
import * as vis from 'vis';
import { Graph2d, PointItem } from 'vis';
import { PostService } from '../services/post.service';
#Component({
selector: 'izoa-db2-chart2',
templateUrl: './db2-chart2.component.html',
styleUrls: ['./db2-chart2.component.scss']
})
export class Db2Chart2Component implements OnInit {
#ViewChild('vizchart') vizchart: ElementRef;
data: Row[] = [];
constructor(private postService: PostService) { }
post.service.ts:
import { Injectable } from '#angular/core';
import { HttpClient, HttpHeaders } from '#angular/common/http';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';
#Injectable({
providedIn: 'root'
})
export class PostService {
constructor(private httpClient: HttpClient) { }
sample-pack-lib.module.ts:
import { NgModule } from '#angular/core';
import { SamplePackLibComponent } from './sample-pack-lib.component';
import { Db2Chart2Component } from './db2-chart2/db2-chart2.component';
import { Db2Chart1Component } from './db2-chart1/db2-chart1.component';
// import { HttpClientModule } from '#angular/common/http';
import {
MatButtonModule,
MatCardModule,
MatMenuModule,
MatToolbarModule,
MatIconModule,
MatSidenavModule,
MatGridListModule,
MatListModule
} from '#angular/material';
#NgModule({
declarations: [
Db2Chart2Component,
SamplePackLibComponent,
Db2Chart1Component
],
imports: [
// HttpClientModule,
MatButtonModule,
MatMenuModule,
MatCardModule,
MatToolbarModule,
MatIconModule,
MatSidenavModule,
MatGridListModule,
MatListModule
],
exports: [
SamplePackLibComponent,
Db2Chart2Component,
Db2Chart1Component
]
})
export class SamplePackLibModule { }
public-api.ts
import { NgModule } from '#angular/core';
import { SamplePackLibComponent } from './sample-pack-lib.component';
import { Db2Chart2Component } from './db2-chart2/db2-chart2.component';
import { Db2Chart1Component } from './db2-chart1/db2-chart1.component';
// import { PostService } from './services/post.service';
// import { HttpClientModule } from '#angular/common/http';
import {
MatButtonModule,
MatCardModule,
MatMenuModule,
MatToolbarModule,
MatIconModule,
MatSidenavModule,
MatGridListModule,
MatListModule
} from '#angular/material';
#NgModule({
declarations: [
Db2Chart2Component,
SamplePackLibComponent,
Db2Chart1Component
],
// providers: [PostService],
imports: [
// HttpClientModule,
MatButtonModule,
MatMenuModule,
MatCardModule,
MatToolbarModule,
MatIconModule,
MatSidenavModule,
MatGridListModule,
MatListModule
],
exports: [
SamplePackLibComponent,
Db2Chart2Component,
Db2Chart1Component
]
})
export class SamplePackLibModule { }
package.json:
{
"name": "sample-pack-lib",
"version": "0.0.1",
"dependencies": {
},
"peerDependencies": {
"#angular/common": "^7.2.0",
"#angular/core": "^7.2.0",
"#angular/material": "7.3.0"
}
}
The main app:
#Component({
selector: 'app-admin',
template: '<button (click)="load()">Load</button><ng-container #vc></ng-container>',
styleUrls: ['./admin.component.scss']
})
export class AdminComponent {
#ViewChild('vc', { read: ViewContainerRef }) vc: ViewContainerRef;
private cfr: any;
constructor(public compiler: Compiler, private injector: Injector, private r: ComponentFactoryResolver) { }
load() {
// register the modules that we already loaded so that no HTTP request is made
// in my case, the modules are already available in my bundle (bundled by webpack)
SystemJS.set('#angular/core', SystemJS.newModule(AngularCore));
SystemJS.set('#angular/common', SystemJS.newModule(AngularCommon));
SystemJS.set('#angular/material',SystemJS.newModule(AngularMaterial));
SystemJS.set('#angular/router', SystemJS.newModule(AngularRouter));
SystemJS.set('vis', SystemJS.newModule(Vis));
SystemJS.set('#angular/common/http', SystemJS.newModule(HttpClientModule));
const url = '../bundles/sample-pack-lib.umd.js';
SystemJS.import(url).then((module) => {
this.compiler.compileModuleAndAllComponentsAsync(module['SamplePackLibModule'])
.then((moduleFactory) => {
const moduleRef = moduleFactory.ngModuleFactory.create(this.injector);
const factory = moduleFactory.componentFactories.find(
item => item.componentType.name === 'SamplePackLibComponent');
if (factory) {
const component = this.vc.createComponent(factory);
const instance = component.instance;
}
});
});
The problem was with the HttpCLientModule.
Previously I imported it that way:
import { HttpClientModule } from '#angular/common/http';
It should be:
import * as HttpClientModule from '#angular/common/http';

Not able to render windbarb Highchart in angular

I am trying to plot wind barb using my angular application. I used angular-highchart package but it's showing me below error -
Error: Highcharts error #17: www.highcharts.com/errors/17
import { Component } from '#angular/core';
import { Chart } from 'angular-highcharts';
import { MapChart } from 'angular-highcharts';
#Component({
selector: 'app-root',
template: `
<div [chart]="chart"></div>
`
})
export class AppComponent {
chart = new Chart({
title : { text : 'simple chart' },
xAxis: {
type: 'datetime',
offset: 40
},
series: [{
type: 'windbarb',
name:"Wind Direction",
data: [
[9.8, 177.9],
[10.1, 177.2]
]
}, {
type: 'area',
name:'WindSpeed',
data: [
[9.8, 177.9],
[10.1, 177.2]
],
}]
});
constructor() {
}
}
here
Check module.ts imports as per angular-highcharts docs
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule } from '#angular/forms';
import { ChartModule, HIGHCHARTS_MODULES } from 'angular-highcharts';
import exporting from 'highcharts/modules/exporting.src';
import windbarb from 'highcharts/modules/windbarb.src';
export function highchartsModules() {
// apply Highcharts Modules to this array
return [ exporting,windbarb ];
}
import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';
#NgModule({
imports: [ BrowserModule, FormsModule,ChartModule ],
declarations: [ AppComponent, HelloComponent ],
providers: [
{ provide: HIGHCHARTS_MODULES, useFactory: highchartsModules } // add as factory to your providers
],
bootstrap: [ AppComponent ]
})
export class AppModule { }
Stackblitz demo

unhandled Promise rejection: No base href set. Please provide a value for the APP_BASE_HREF token or add a base element to the document

i work on a angular 4 project as front end for an asp.net MVC and API in the same solution when i set my routes i get the above error.
my code as following
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { RouterModule, Routes } from '#angular/router';
import { DashboardComponent } from
'../../Components/dashboard/dashboard.component';
import { TraitComponent } from '../../Components/trait/trait.component';
const routes: Routes = [
{ path: ' ', redirectTo: '/dashboard', pathMatch: 'full' },
{ path: 'dashboard', component:DashboardComponent },
{ path: 'Trait', component: TraitComponent },
//{ path: 'heroes', component: }
];
#NgModule({
imports: [
RouterModule.forRoot(routes) ,
CommonModule
],
exports: [RouterModule],
})
export class MyAppRoutingModuleModule {
i register/import the "myapprouting "and in my appmodule
that is code in my appComponent
<nav>
<a routerLink="localhost:56800/dashboard">Dashboard</a>
<a routerLink="localhost:56800/Trait">Heroes</a>
</nav>
<!-- <app-trait></app-trait>-->
<router-outlet>
</router-outlet>
In your app.module.ts, add the following :
{provide: APP_BASE_HREF, useValue: '/'}
to your **providers : [ ] ** so it would be like this :
providers: [{provide: APP_BASE_HREF, useValue: '/'},SomeService,AnotherService]
app.module.ts
import { APP_BASE_HREF } from '#angular/common'; <-- add those ***
const appRoutes: Routes = [
{ path: 'secondpage', component: SecondPageComponent },
];
#NgModule({
declarations: [
AppComponent,
NameEditorComponent,
ProfileEditorComponent,
SecondPageComponent
],
imports: [
BrowserModule,
// other imports ...
ReactiveFormsModule,
RouterModule.forRoot(
appRoutes,
{ enableTracing: true } //
)
],
providers: [{provide: APP_BASE_HREF, useValue: '/'}], <-- add those **** bootstrap: [AppComponent]
})
export class AppModule { }
Try to change the routerLink to this :
[routerLink]="['/dashboard']
[routerLink]="['/Trait']

NullInjectorError: No provider for HttpClient! Angular 5

I, am using the Angular template in visual studio 2017. Then I updated to angular 5.2. I, tried to find the solution. But didn't got exact solution.
The service class is calling the http call.However I, am getting an error as
Service.TS
import { Injectable } from '#angular/core';
import { LoginViewModel as loginVM } from "../../viewmodel/app.viewmodel"
import { HttpClient, HttpHeaders } from "#angular/common/http";
#Injectable()
export class LoginService {
private loginUrl = "Account/Authentication";
private _httpClientModule: HttpClient;
constructor(httpClientModule: HttpClient) {
this._httpClientModule = httpClientModule;
}
public LoginHttpCall(_loginVM: loginVM) {
const headers = new HttpHeaders().set('Content-Type', 'application/json; charset=utf-8');
this._httpClientModule.post(this.loginUrl, _loginVM, { headers }).
subscribe(data => {
console.log(data);
},
err => {
console.log("Error occured.");
});
}
}
Here is my Component class
import { Component } from '#angular/core';
import { AppComponent } from "../app/app.component";
import { LoginService } from "../../service/account/app.service.account.login";
import { LoginViewModel } from "../../viewmodel/app.viewmodel";
declare var componentHandler: any;
#Component({
selector: 'login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css'],
providers: [LoginViewModel, LoginService]
})
export class LoginComponent {
private _appComponent: AppComponent;
private _loginService: LoginService;
constructor(private appComponent: AppComponent, loginService: LoginService) {
this._appComponent = appComponent;
this._appComponent.menulist = false;
this._loginService = loginService;
}
}
app.shared.module.ts
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { FormsModule } from '#angular/forms';
import { HttpModule } from '#angular/http';
import { RouterModule } from '#angular/router';
import { AppComponent } from './components/app/app.component';
import { HomeComponent } from './components/home/home.component';
import { LoginComponent } from './components/login/login.component';
import { MobileComponent } from './components/mobile/mobile.component';
#NgModule({
declarations: [
AppComponent,
HomeComponent,
LoginComponent,
MobileComponent
],
imports: [
CommonModule,
HttpModule,
FormsModule,
RouterModule.forRoot([
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent },
{ path: 'login', component: LoginComponent },
{ path: 'mobile', component: MobileComponent },
{ path: '**', redirectTo: 'home' }
])
]
})
export class AppModuleShared {
}
I, don't know where I, am doing mistake. Since I , am new in angular. I tried to add HttpClient under #NgModule but gives some other error . Since As per my knowledge I don't need to add in app.shared.module.ts file. Since HttpClient is used in service and component level.
Can anyone please tell me where I, am doing wrong .
HttpClient needs for the module HttpClientModule instead of HttpModule to be imported and added in the imports of the module.
For more see Documentation
import { HttpClientModule } from '#angular/common/http';
#NgModule({
declarations: [
...
],
imports: [
...
HttpClientModule,
...
]
})
export class AppModuleShared { }
npm clear cache
npm update
rm -rf /node_modules
npm i --save
Then import same module into app root module.
Hope it works for you.

Resources