I am working on Electron app with angular 5 for the rendering process,
is there is a way to export the console programmatically?
I need a way to synchronize the logging data to file so, I can review it anytime
without opening electron devtools and save as option, I need it programmatically
I save my own logs, but what if there is a module that logging an error i need to get whole console log history and export it to log file
You can use electron-log, which is a logging module for Electron application. It can be used without Electron.
And you should use ngx-electron.
Firstly, install electron-log
npm install electron-log
Require it in the electron's main process.
const logger = require('electron-log');
Then install ngx-electron
npm install ngx-electron
ngx-electron is exposing a module called NgxElectronModule which needs to be imported in your AppModule.
import {NgModule} from '#angular/core';
import {BrowserModule} from '#angular/platform-browser';
import {NgxElectronModule} from 'ngx-electron';
import {AppComponent} from './app.component';
#NgModule({
declarations: [],
imports: [
BrowserModule,
NgxElectronModule
],
bootstrap: [AppComponent]
})
export class AppModule {
}
Once the module has been imported, you can easily use angular DI to ask for ElectronService.
import {Component} from '#angular/core';
import {ElectronService} from 'ngx-electron';
#Component({
selector: 'my-app',
templateUrl: 'app.html'
})
export class AppComponent {
logger
constructor(private _electronService: ElectronService) {
// this should be in init()
if(this._electronService.isElectronApp) {
this.logger = this._electronService.remote.require("electron-log");
}
}
public testLogger() {
this.logger.info('this is a message from angular');
}
}
After that, you should be able to use electron-log in your components, just remember import {ElectronService} from 'ngx-electron';, and this.logger = this._electronService.remote.require("electron-log"); in the components.
Related
I was just trying to build a module/component and serve it as a JS bundle. it builds:
#Component({
selector: 'app-component-overview',
template: '<button><ng-content></ng-content></button>',
})
export class ButtonComponent {}
#NgModule({
declarations: [ButtonComponent],
})
export class AppModule {}
the issue is that after building it to a javascript bundle. when I try to import it in another angular project. I get:
//ERROR in ... error TS2306 '...' is not a module.
loadChildren: () => import('...').then(m=>m.ButtonModule)
maybe I am missing the point here and things are different in angular, having webpack control makes it a lot easier but I want to avoid bringing custom builders and fiddling with the settings as little as possible.
Question is, is there a well documented way to bundle a module or even a standalone component to be used outside my project as a JS bundle? I could not find anything useful other than high level explanation of reusing and lazyloading thing already inside the same project.
It seems you are building this module as part of an application which is supposed to run in a browser. But what you are looking for is to build this module as part of a library which can be re-used in other projects.
See this official Angular guide on how to create a library.
After a few hours browsing around. I figured it out.
The answer that #json-derulo gave is part of the solution but there are more steps to make this work.
follow the guide: https://angular.io/guide/creating-libraries
here is the tricky part if you import the lib inside the workspace it will work. but that does not make much sense. You likely have another repository with a angular app that you want to consume the lib.
now to be able to import the this component as a lazy loaded route you will need to add "#angular/router" to the lib peerDependecies and run npm install again
now create a routing module and add the empty path to point to the component in the lib.
//my-lib-routing.module.ts
import { NgModule} from "#angular/core";
import { RouterModule } from "#angular/router";
import { MyLibComponent } from "./my-lib.component";
const routes= [
{ path: '', component: MyLibComponent },
];
#NgModule({
imports: [
RouterModule.forChild(
routes,
)
// other imports here
],
// providers: [RouterModule],
exports: [RouterModule]
})
export class myLibRoutingModule { }
change the libmodule to import the routing module
//
import { NgModule } from '#angular/core';
import { myLibRoutingModule } from './my-lib-routing.module';
import { MyLibComponent } from './my-lib.component';
#NgModule({
declarations: [MyLibComponent],
imports: [
myLibRoutingModule
],
})
export class MyLibModule { }
on the lib project root run 'npm run build'.
create a separate repo and "ng new app"
add the lib to the package.json of the main app, something like "my-lib": "../my-lib-ws/dist/my-lib".
open angular.json and add "preserveSymlinks": true to the build options.
run npm i to link the lib as a dependency.
add the libmoudle as a lazy loaded route
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
const routes: Routes = [
{path: 'test', loadChildren: () => import('my-lib').then(m=>m.MyLibModule)}
];
#NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
run npm run start. and try to access the 'test' route. you should see the component loaded in the main app router outled
Now, this is more of learning exercise the bundles almost gets doubled. and you would profit more using module federation. But it is a use case we have. Anyhow the steps are here if anyone can't reproduce let me know.
Current behavior
I declared those dynamic components as entry components in the module where I also want to render them. With JIT it works fine.
Following structure has the part of my app I want to render them: app -> home (lazy) -> contracts (lazy) -> search.
So I added those components to the module I use for the search component/route. When I'm compiling with AOT, everytime I visit the search route, the app tells me there is no component factory. Of course I searched google and found some results:
I tried adding them to the ANALYZE_FOR_ENTRY_COMPONENTS provider, I tried to import a ModuleWithProviders with .forRoot() in my app.module and I also tried simply importing and declaring my dynamic and all of its dependant components in the root module (app.module). Everything resulting in the same error.
I declare my dynamic components as entry components like so:
#NgModule({
imports: [SharedComponentsModule, FinoSchemaFormsModule, TabGroupModule, FinoInputModule],
declarations: [EnergySearchSettingsComponent, DslSearchSettingsComponent, MobileSearchSettingsComponent, ComparisonDetailSectionComponent],
entryComponents: [EnergySearchSettingsComponent, DslSearchSettingsComponent, MobileSearchSettingsComponent],
exports: [EnergySearchSettingsComponent, DslSearchSettingsComponent, MobileSearchSettingsComponent, ComparisonDetailSectionComponent],
providers: [CategoryMappingProvider]
})
export class ComparisonComponentsModule { }
This module gets imported in the SearchModule, where also my SearchComponent is declared. In this component I want to render those components dynamically using the ComponentFactoryResolver I inject in the SearchComponent.
ngOnInit() {
this.searchSettingsComponent = this.comparisonService.getSearchComponent(); // returns either EnergySearchSettingsComponent, DslSearchSettingsComponent or MobileSearchSettingsComponent
let componentFactory = this.componentFactoryResolver.resolveComponentFactory(searchSettingsComponent);
this.searchSettingsComponent = this.searchContainer.createComponent(componentFactory);
this.searchSettingsComponent.instance.comparisonSettings = comparisonSettings;
this.searchSettingsComponent.instance.onSave.subscribe(settings => this.saveSearchSettings(settings));
}
The SearchComponent is the routing component of the search route, which is a child route of my contract route, which gets lazy loaded. This again is a child route of my home route (also lazy loaded) and this belongs to the main route.
Environment
Angular version: 5.2.4
For Tooling issues:
- Node version: 8.11.3
- Platform: Mac
It must be pretty simple. Just create the SharedModule and put all reusable dynamic component in it, export those components from SharedModule and import this Module in all required. Lazy loaded Modules.
Since it is imported direct to the Module, it must be available while creating the Dynamic Component.
Have you tried updating angular to latest 6.1.10? With version 5 I had issues with lazy loaded modules.
I had a similar task, and it worked fine under 6.1.4.
I've created a working example for you under 7.0.1
I've created both cases
Dynamic component is declared in the module which will create the dynamic component
Dynamic component is declared in a shared module and imported in the lazy-loaded module which will create dynamic components. You can create a shared module for every dynamic component, so you import only one component in a lazy loaded module
I don't feel as though there is enough information in your question to give you the exact answer to the problem you are facing.
I was able to create a solution with, what I feel is a similar setup to yours that you could use to solve your problem or to ask a more pointed question.
TLDR: Full GitHub repo here
I created an app structure as follows:
app/
app.module
app.component
/dynamic-provider --contains component that is dynamically loading other components
--module is lazy loaded by dynamic-one module
dynamic-loader.module
slot.component
/dynamic-one --contains lazy loaded module
--module is lazy loaded by app module
dynamic-one.module
/dynamic-loader --contains a component to be dynamically loaded
dynamic-provider.module
one.component
provider.service
app.module looks as follows
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { RouterModule } from '#angular/router';
import { AppComponent } from './app.component';
#NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
RouterModule.forRoot([
{ path: 'dynamic-loader', loadChildren: './dynamic-one/dynamic-one.module#DynamicOneModule' },
{ path: '', component: AppComponent }
])
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
dynamic-one.module looks as follows
import { NgModule } from '#angular/core';
import { RouterModule } from '#angular/router';
#NgModule({
imports: [
RouterModule.forChild([
{ path: '', loadChildren: '../dynamic-loader/dynamic-loader.module#DynamicLoaderModule' }
])
]
})
export class DynamicOneModule {
constructor() {
console.log('one');
}
}
dynamic-loader.module looks as follows
import { NgModule } from '#angular/core';
import { RouterModule } from '#angular/router';
import { DynamicProviderModule } from '../dynamic-provider/dynamic-provider.module';
import { SlotComponent } from './slot.component';
#NgModule({
declarations: [ SlotComponent ],
imports: [
DynamicProviderModule,
RouterModule.forChild([
{ path: '', component: SlotComponent }
])
]
})
export class DynamicLoaderModule { }
dynamic-provider.module looks as follows
import { NgModule } from '#angular/core';
import { OneComponent } from './one.component';
import { ProviderService } from './provider.service';
#NgModule({
declarations: [ OneComponent ],
entryComponents: [ OneComponent ],
exports: [ OneComponent ],
providers: [ ProviderService ]
})
export class DynamicProviderModule { }
As you state, your dynamic creation of components is working when the module isn't loaded, so I haven't included that code here(though it is in the repo for completeness). As can be seen here though, the app module lazy loads the dynamic-one module which in turn lazy loads the dynamic-loader module. The dynamic-loader module dynamically creates components from the dynamic-provider module.
How this differs from your implementation is very hard to tell as you have provided only a small amount of information. I hope this helps you find the missing piece you are looking for though!
Creating shared modules allows you to organize and streamline your
code. You can put commonly used directives, pipes, and components into
one module and then import just that module wherever you need it in
other parts of your app.
By re-exporting CommonModule and FormsModule, any other module that imports this SharedModule, gets access to directives like NgIf and NgFor from CommonModule and can bind to component properties with [(ngModel)], a directive in the FormsModule.
EX:
import { CommonModule } from '#angular/common';
import { NgModule } from '#angular/core';
import { ReactiveFormsModule } from '#angular/forms';
import { SharedModule } from '../../shared/shared.module';
import { EntryModalComponent } from './entry-modal.component';
#NgModule({
imports: [
CommonModule,
SharedModule,
ReactiveFormsModule
],
declarations: [ EntryModalComponent ],
entryComponents: [ EntryModalComponent ],
exports: [ EntryModalComponent ]
})
export class EntryModalModule { }
Now you can use this EntryModalComponent for dynamic loading in some other component after importing the module where it's defined.
In the latest versions Angular has updated a lot of staff about lazy loaded modules. And with high probability this trouble is fixed now.
I'm having trouble setting up the dependencies for a component that includes an ng bootstrap modal. The following code is from a test project that isolates the issue. The component works and runs with no errors when the website is served but there seems to be a dependency issue with the tests. I'm using the NgbModal service to open and close the modal within the component. Here's the setup of the component:
#Component({
selector: 'app-main-component',
templateUrl: './main.component.html',
styleUrls: ['./main.component.css'],
providers: [ NgbModal ]
})
export class MainComponent implements OnInit {
constructor(private modalService: NgbModal) { }
and here's where the dependencies are set up in the app.module.ts:
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppComponent } from './app.component';
import { MainComponent } from './main/main.component';
import { NgbModule } from '#ng-bootstrap/ng-bootstrap';
#NgModule({
declarations: [
AppComponent,
MainComponent
],
imports: [
BrowserModule,
NgbModule.forRoot()
],
bootstrap: [AppComponent]
})
and the dependencies for the testbed are set up in the main.component.ts file here:
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ MainComponent ],
imports: [ NgbModule.forRoot(), BrowserModule ],
providers:[ NgbModal ]
})
.compileComponents();
component = TestBed.get(MainComponent);
modalService = TestBed.get(NgbModal);
}));
When I try to run the tests it's giving me this error
Failed: StaticInjectorError(DynamicTestModule)[NgbModal -> NgbModalStack]:
StaticInjectorError(Platform: core)[NgbModal -> NgbModalStack]:
NullInjectorError: No provider for NgbModalStack!
which seems to imply there's a missing dependency. With errors like this in the main app it seems like it's usually caused by the NgbModule.forRoot() not getting imported but it's in the imports for the test.
Thank you for your time.
Turns out the issue wasn't in my main component spec file, it was an issue running the test for my app component spec file. Since the component was used in the main app component it needed to have the same imports in the app component spec file.
I have a huge angular 2 appliucation.
for every two weeks we are giving a patch release.
but everytime users need to clear the browser cache to see the js changes.
is there any inbuild method in angular 2 or js or jquery where users can delete the cache automatically when they hit the url in the browser after our release.
I thought of including that method in the below app.module.ts file since it includes all the modules
can you tell me how to solve the problem.
import './rxjs-extensions';
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule,ReactiveFormsModule } from '#angular/forms';
import { HttpModule } from '#angular/http';
import { AppComponent } from './app.component';
import {Base} from './components/base/base';
import {playerUser} from './components/player/user';
import {player} from './components/player/player';
import {
Routes,
RouterModule,
Router,
ActivatedRoute,
CanActivateChild,
CanDeactivate,
ActivatedRouteSnapshot,
RouterStateSnapshot
} from "#angular/router";
import { titleService } from './components/title/titleService';
#NgModule({
imports: [
BrowserModule,
FormsModule,
ReactiveFormsModule,
HttpModule,
routing,
MultiselectDropdownModule,
AccordionModule
],
declarations: [
AppComponent,
Base,
player,
playerUser,
playerFunctionalRoles,
],
providers: [
sportsUService,saveService,titleService],
bootstrap: [ AppComponent ]
})
export class AppModule {
}
What are you using to bundle your application?
If you are using angular cli, then cache busting mechanisms are in place (notice that the generated files have a hash associated with them). In which case you can disable caching within Nginx/Apache or whatever you are using to serve your site on index.html only.
This will download the new source files identified by the new hash code reference within the index.html.
In case you are using webpack only, make sure that cache busting is enabled .
This tutorial : https://powerspace.tech/how-to-cache-busting-with-webpack-5131b4af8826 shows you how to enable hashing and cache busting.
I want to make my website modern with some cool features.
For this I used jQuery and self made things. But that's slow and everything I developed is easier in Angular.
So I started to implement the Angular 2 code into my normal website.
The things (app.component, main.ts, app.module) work. I have the angular functionality on my page.
That's the first try.
Now I found out that I can't use second and third components (this ones which are not in bootstrap array) not within the selector.
So the bootstrapped component is the root-element for everything I think.
The next step was to replace the whole body as a component.
For example with angular 1 it was easy: ng-controller="app" and finish.
I can do this with <body> and everything.
Now with Angular 2 I must define a template for the component. else I get this error Uncaught Error: No template specified for component AppComponent
So the questions are...
Is it possible to use the as selector for the app so that I can use components within the app without bootstrapping them?
Or is there a way to use the components flexible?
The main reason is:
I want to define components globally which must not exist on each page. So I can have a component which is called test-component which is only used on test.html and a about-component which is only used on about.html
You understand?
Currently the problem is that I get this error: app.js:116448EXCEPTION: Error in :0:0 caused by: The selector "my-app" did not match any elements and ORIGINAL EXCEPTION: The selector "my-app" did not match any elements
If I define them both it works. But if one component is missing then I get this error.
Current scripts:
main.ts
import { platformBrowserDynamic } from '#angular/platform-browser-dynamic';
import { AppModule } from './app.module';
platformBrowserDynamic().bootstrapModule(AppModule);
app.component.ts
import { Component } from '#angular/core';
import {Http} from "#angular/http";
#Component({
selector: 'my-app',
template: `<h1>Hello {{name}}</h1> <a (click)="test()">:)</a>`
})
export class AppComponent {
constructor (private http: Http) {}
name = 'Angular';
test() {
alert('Yay');
return this.http.get('/asd/aaa/test').subscribe((a) => {
console.log('A', a);
}, (b) => {
console.log('B', b);
});
}
}
app.module.ts
import {NgModule} from '#angular/core';
import {BrowserModule} from '#angular/platform-browser';
import {AppComponent} from './app.component';
import {JsonpModule, HttpModule} from "#angular/http";
import {FormsModule} from "#angular/forms";
import {TestComponent} from "./test.component";
#NgModule({
imports: [
BrowserModule,
FormsModule,
HttpModule,
JsonpModule
],
declarations: [
AppComponent,
TestComponent
],
bootstrap: [
AppComponent,
// TestComponent // this shouldnt be a bootstrap because else the component MUST exist on the page!
]
})
export class AppModule {
}
test.component.ts
import { Component } from '#angular/core';
import {Http} from "#angular/http";
#Component({
selector: 'test-app',
template: `<h1>Hello {{name}}</h1> <a (click)="test()">:)</a>`
})
export class TestComponent {
constructor (private http: Http) {}
name = 'Angular !!!!!!!!!!!!';
test() {
alert('yyyyy');
return this.http.get('/asd/aaa/test').subscribe((a) => {
console.log('A', a);
}, (b) => {
console.log('B', b);
});
}
}
As I said if I want to use the body as root element it replaces everything of the body. And this is not for my use case.
It's only a normal website. Multiple HTML (background = PHP) pages.
I could implement this platformBrowserDynamic().bootstrapModule(AppModule); on each page where I need something. Then I could write a module for each page. I think this could solve the problem, too. But it's bad... Having a lot of modules...