Angular 2 - Import html2canvas - node.js

I have installed html2canvas on my angular 2 project using npm install html2canvas --save. If I now go to any file and write import * as html2canvas from 'html2canvas' it gives the error:
Cannot find module 'html2canvas'
My package file looks like this:
{
...
"scripts": {
...
},
"dependencies": {
...
"html2canvas": "^0.5.0-beta4",
...
},
"devDependencies": {
...
}
}
The file on which I'm trying to import the html2canvas is:
import { Injectable } from '#angular/core';
import * as jsPDF from 'jspdf';
import * as html2canvas from 'html2canvas';
#Injectable ()
export class pdfGeneratorService {
...
}

Since Angular2 uses typescript, you need to install the typescript definition files for that module.
It can be installed from #types (if it exists). If it doesn't you can create your own definition file and include it in your project.

in angular 9 i use it this way:
import html2canvas from 'html2canvas';
....
html2canvas(this.head2print.nativeElement).then(_canvas => {
hdr = _canvas.toDataURL("image/png");
});

Also, the onrendered option for callback function may not work. Instead, you may use "then" as below:
html2canvas(document.body).then((canvas) => {
document.body.appendChild(canvas);
});
https://stackoverflow.com/a/45366038/3119507

Ran into the same issue running Angular 8. It still didn't work after installing the #types. What worked for me was to include the html2canvas library using require instead.
const html2canvas = require('../../../node_modules/html2canvas');
Then to take the screenshot:
#ViewChild('screenshotCanvas') screenCanvas: ElementRef;
html2canvas(this.screenCanvas.nativeElement).then(canvas => {
var imgData = canvas.toDataURL("image/png");
console.log("ENTER takeScreenshot: ",imgData )
document.body.appendChild(imgData);
})

Related

The injectable 'PlatformLocation' needs to be compiled using the JIT compiler, but '#angular/compiler' is not available

My Angular application is served via Node 16.13.0. After updating to Angular 13, I'm receiving the following error:
JIT compilation failed for injectable [class PlatformLocation]
file:///Users/btaylor/work/angular-apps/dz-outages-ui/node_modules/#angular/core/fesm2015/core.mjs:4058
throw new Error(message);
^
Error: The injectable 'PlatformLocation' needs to be compiled using the JIT compiler, but '#angular/compiler' is not available.
The injectable is part of a library that has been partially compiled.
However, the Angular Linker has not processed the library such that JIT compilation is used as fallback.
Ideally, the library is processed using the Angular Linker to become fully AOT compiled.
Alternatively, the JIT compiler should be loaded by bootstrapping using '#angular/platform-browser-dynamic' or '#angular/platform-server',
or manually provide the compiler with 'import "#angular/compiler";' before bootstrapping.
at getCompilerFacade (file:///Users/btaylor/work/angular-apps/dz-outages-ui/node_modules/#angular/core/fesm2015/core.mjs:4058:15)
at Module.ɵɵngDeclareFactory (file:///Users/btaylor/work/angular-apps/dz-outages-ui/node_modules/#angular/core/fesm2015/core.mjs:32999:22)
at file:///Users/btaylor/work/angular-apps/dz-outages-ui/node_modules/#angular/common/fesm2015/common.mjs:90:28
at ModuleJob.run (node:internal/modules/esm/module_job:185:25)
at async Promise.all (index 0)
at async ESMLoader.import (node:internal/modules/esm/loader:281:24)
at async loadESM (node:internal/process/esm_loader:88:5)
at async handleMainPromise (node:internal/modules/run_main:65:12)
I have tried numerous solutions, such as: Angular JIT compilation failed: '#angular/compiler' not loaded
Currently, I have "type": "module" in my package.json
I have updated my postinstall command to: ngcc --properties es2020 browser module main --first-only --create-ivy-entry-points
I also added import '#angular/compiler'; to my main.ts file.
The project will compile, but won't run via Node.
I believe I have found the solution (presuming you are using jest as your test runner). In the test-setup.ts file my project still was using the outdated import for jest-preset-angular. Instead of import 'jest-preset-angular'; try using import 'jest-preset-angular/setup-jest';.
This addressed the issue for me.
It seems angular 13 made babel-loader a mandatory requirement to link Ivy-native packages. https://github.com/angular/angular/issues/44026#issuecomment-974137408 - and the issue is happening as core Angular libraries are already compiled with the Ivy package format.
I haven't yet made the change in my own projects, but processing .mjs files with babel and a special linker should be enough.
import { dynamicImport } from 'tsimportlib';
/**
* Webpack configuration
*
* See: http://webpack.github.io/docs/configuration.html#cli
*/
export default async (options: IWebpackOptions) => {
const linkerPlugin = await dynamicImport('#angular/compiler-cli/linker/babel', module);
const config: any = {
module: {
rules: [{
test: /\.mjs$/,
loader: 'babel-loader',
options: {
compact: false,
plugins: [linkerPlugin.default],
},
resolve: {
fullySpecified: false
}
}
}
}
}
I'll make more updated to this post once I am able to test it myself.
If I correctly understand, you use Angular Universal also.
I want to share my experience with the same problem which came to my project after updating Angular from v8 to v13.
First of all, I want to say that the main problem was with the incorrect started file for SSR. In my project, it was server.js and now it's main.js.
So, maybe your project also tries to start from the incorrect file which doesn't have the necessary code to start it.
More details:
I updated the project step by step, increasing the version as recommended by the Angular team and according to https://update.angular.io/?l=3&v=8.2-13.0
Unfortunately, at every step, I only checked the version of SPA without SSR and only compiled the project to check that all is OK, but didn't start it with SSR. Now I can't say when the problem with the JIT compiler started.
And when I finished updating and fixing bugs with SPA, compiled the project with SSR, and tried to start it I saw this problem:
Error: The injectable 'PlatformLocation' needs to be compiled using the JIT compiler, but '#angular/compiler' is not available.
I tried different solutions like you, but nothing helped. After that, I created a new clean project with ng13 and added Angular Universal. And compare my project with new, generated by Angular-CLI.
What I changed in my project(sorry, I can't show the project - NDA):
angular.json
"projects": {
"projectName": {
...
"architect": {
...
"server": {
...
"options": {
"outputPath": "dist/server",
//"main": "src/main.server.ts", //removed
"main": "server.ts", //added
...
}
}
}
}
}
package.json
"scripts": {
...
//"serve:production:ssr": "node dist/server --production" // removed. It was incorrect file server.js which gave the error from this case
"serve:production:ssr": "node dist/server/main --production", // added
...
"postinstall": "ngcc --properties es5 browser module main --first-only" // added. In my case, actual version is es5
}
3.server.ts
import 'zone.js/node';
import { ngExpressEngine } from '#nguniversal/express-engine';
import * as express from 'express';
import { join } from 'path';
import { AppServerModule } from './src/main.server';
...
// after all imports I inserted previous code into function run()
...
export function run() {
// previous code from project with some small changes
}
//and added next code from clean project:
// Webpack will replace 'require' with '__webpack_require__'
// '__non_webpack_require__' is a proxy to Node 'require'
// The below code is to ensure that the server is run only when not requiring the bundle.
declare const __non_webpack_require__: NodeRequire;
const mainModule = __non_webpack_require__.main;
const moduleFilename = mainModule && mainModule.filename || '';
if (moduleFilename === __filename || moduleFilename.includes('iisnode')) {
run();
}
export * from '../src/main.server';
src/main.server.ts
// was only:
export { AppServerModule } from './app/app.server.module';
// replaced by code from clean project:
/***************************************************************************************************
* Initialize the server environment - for example, adding DOM built-in types to the global scope.
*
* NOTE:
* This import must come before any imports (direct or transitive) that rely on DOM built-ins being
* available, such as `#angular/elements`.
*/
import '#angular/platform-server/init';
import { enableProdMode } from '#angular/core';
import { environment } from './environments/environment';
if (environment.production) {
enableProdMode();
}
export { AppServerModule } from './app/app.server.module';
export { renderModule, renderModuleFactory } from '#angular/platform-server';
src/main.ts
...
//this part of code
document.addEventListener("DOMContentLoaded", () => {
platformBrowserDynamic()
.bootstrapModule(AppModule)
.catch(err => console.log(err));
});
// replaced by
function bootstrap() {
platformBrowserDynamic().bootstrapModule(AppModule)
.catch(err => console.error(err));
};
if (document.readyState === 'complete') {
bootstrap();
} else {
document.addEventListener('DOMContentLoaded', bootstrap);
}
//but I don't think it plays a role in solving the JIT problem. Wrote just in case
tsconfig.server.json
{
"extends": "./tsconfig.app.json",
"compilerOptions": {
"outDir": "./out-tsc/app-server",
"module": "commonjs",// it's only in my case, I don't have time for rewrote server.ts now
"types": ["node"],
},
"files": [
"src/main.server.ts",
"server.ts"
],
"include":["server/**/*.ts","node/*.ts"],
"angularCompilerOptions": {
"entryModule": "./src/app/app.server.module#AppServerModule"
}
}
Ok, I think that's all. After all these edits I don't have file /dist/server.js and start the project from /dist/server/main.js without error from this case.
N.B.: When I was updating the project step-by-step I noticed that the process of updating nguniversal by Angular-CLI didn't change anything in the project. Only the version of packages. That's why I recommend comparing your project with an actual clean project manually

cant import createBatchingNetworkInterface from apollo-client

I am trying to integrate graphql with my vue project.
I am following these instructions: https://github.com/Akryum/vue-apollo
I have npm installed 'apollo-client' as required, but for some reason i can't import 'createBatchingNetworkInterface'.
this is my main.js file:
import Vue from 'vue'
import { ApolloClient, createBatchingNetworkInterface } from 'apollo-client'
import VueApollo from 'vue-apollo'
import App from './App'
import router from './router'
and this is the index.d.ts file of my apollo-client:
export { print as printAST } from 'graphql/language/printer';
export { ObservableQuery, FetchMoreOptions, UpdateQueryOptions, ApolloCurrentResult } from './core/ObservableQuery';
export { WatchQueryOptions, MutationOptions, SubscriptionOptions, FetchPolicy, FetchMoreQueryOptions, SubscribeToMoreOptions, MutationUpdaterFn } from './core/watchQueryOptions';
export { NetworkStatus } from './core/networkStatus';
export * from './core/types';
export { ApolloError } from './errors/ApolloError';
import ApolloClient, { ApolloClientOptions } from './ApolloClient';
export { ApolloClientOptions };
export { ApolloClient };
export default ApolloClient;
I don't see here the 'createBatchingNetworkInterface' desired object.
I don't know what am i doing wrong here.
It sounds like you're using Apollo Client 2.0.You should downgrade to an older version (1.9.3) to continue using network interfaces, including the batching one.
The newest version of the client uses Links instead. You can check out the upgrade guide here if you are interested. you can still batch requests in 2.0 using apollo-link-batch-http.

Can not import my custom typescript npm package

I make a typescript npm package, simply like this:
Core.ts
class Core{
constructor(){}
//some functions
}
export = Core;
Core.d.ts
declare class Core {
constructor(){}
//some functions
}
export = Core;
Package.json
{
"name": "#company/Core",
"main": "dist/Core.js",
"typings": "dist/Core" //.d.ts
//etc
}
I make this module with webpack and ts-loader.
In my project, index.ts
import Core = require('#company/Core');
let core = new Core(); //Error, Core is not a function
I have tried to change export and import in some form but no luck. Do I miss some knowlage?
Finally, I solve my promble by myself. I add two properties in webpack configuration file, then recompile it and works well.
webpack.config.js
module.exports = {
output: {
libraryTarget: 'commonjs'
}
//etc
}

node-forge import in angular 2 service

I am trying to use Forge (https://github.com/digitalbazaar/forge) in my Angular 2 project.
I ran the following command :npm install node-forge
This command created the node-forge directory in my application (in the node-modules directory).
I added the node-forge reference in my package.json file: "node-forge": "0.6.39" (dependencies section).
Now, i want to import the node-forge dependency in my angular 2 service (typescript file) with the following code:
import { Injectable } from '#angular/core';
import { Forge } from 'node-forge';
#Injectable()
export class HashPasswordService {
constructor() {}
buildHash(input: string) {
var hmac = forge.hmac.create();
hmac.start('sha512', input);
hmac.update(input);
return hmac.digest().toHex();
}
}
but the import does not work : import { Forge } from 'node-forge'; and i have the following errors in the console (ng serve command):
hash-password.service.ts (2, 23): Cannot find module 'node-forge'.
hash-password.service.ts (11, 16): Cannot find name 'forge'.
So, someone know how i can import this node-forge dependency (use a npm package)? Do I miss a step in my process ?
Thanks for your help !
Just import * as forge from 'node-forge', that's it.
You need the typescript definitions as well as the npm package..
I'm not sure if this package has a DefinitelyTyped package so you can try
npm install typings -g
typings install node-forge
If this doesn't work try:
import { Injectable } from '#angular/core';
declare var Forge: any;
#Injectable()
export class HashPasswordService {
private forge: any;
constructor() {
this.forge = new Forge();
}
buildHash(input: string) {
var hmac = forge.hmac.create();
hmac.start('sha512', input);
hmac.update(input);
return hmac.digest().toHex();
}
}
Install these two packages
npm install node-forge
npm install #types/node-forge
and import * as forge from 'node-forge', that's all...You are good to go.
This is because 'node-forge' is a CommonJS module, which may not support all module.exports as named exports.
CommonJS modules can always be imported via the default export.
The following works for me:
import pkg from 'node-forge';
const {pkcs5, cipher, util} = pkg;

How to load google maps javascript api in Aurelia javascript application?

I found npm module google-maps-api and installed it (npm install google-maps-api) but I can't figure out how to import it with systemjs/jspm (jspm cannot find this module). Here's the configuration from my config.js:
"paths": {
"*": "app/dist/*.js",
"github:*": "app/jspm_packages/github/*.js",
"npm:*": "app/jspm_packages/npm/*.js" }
So, when I try do something like this:
import {mapsapi} from 'google-maps-api';
I get the following error in browser console:
GET https://localhost:44308/app/dist/google-maps-api.js 404 (Not Found)
Looking at the filesystem I see that npm installed the module under app/node_modules/google-maps-api so how do I reference it in the import clause from Aurelia module?
I found a solution and answering my own question here:
I finally figured how to install it with jspm, so you just need to give a hint to jspm to install it from npm like so:
jspm install npm:google-maps-api
After jspm completes installation, import (no {} syntax) works fine:
import mapsapi from 'google-maps-api';
then I inject it in constructor and instantiate geocoder api:
#inject(mapsapi('InsertYourGMAPIKeyHere'))
export class MyClass {
constructor(mapsapi) {
let that = this;
let maps = mapsapi.then( function(maps) {
that.maps = maps;
that.geocoder = new google.maps.Geocoder();
});
...
}
In order to create map on a div I use EventAggregator to subscribe for router:navigation:complete event and use setTimeout to schedule map creation:
this.eventAggregator.subscribe('router:navigation:complete', function (e) {
if (e.instruction.fragment === "/yourRouteHere") {
setTimeout(function() {
that.map = new google.maps.Map(document.getElementById('map-div'),
{
center: new google.maps.LatLng(38.8977, -77.0366),
zoom: 15
});
}, 200);
}
});
Here's a complete view-model example that uses attached() to link to your view.
import {inject} from 'aurelia-framework';
import mapsapi from 'google-maps-api';
#inject(mapsapi('your map key here'))
export class MapClass {
constructor(mapsAPI) {
this.mapLoadingPromise = mapsAPI.then(maps => {
this.maps = maps;
});
}
attached() {
this.mapLoadingPromise.then(() => {
var startCoords = {
lat: 0,
long: 0
};
new this.maps.Map(document.getElementById('map-div'), {
center: new this.maps.LatLng(startCoords.lat, startCoords.long),
zoom: 15
});
});
}
}
For everyone using Typescript and getting "Cannot find module 'google-maps-api'" error,
you need to add typings to the solution. Something like this works
declare module 'google-maps-api' {
function mapsapi(apikey: string, libraries?, onComplete?);
namespace mapsapi {
}
export = mapsapi;
}
and then import it like this
import * as mapsapi from 'google-maps-api';

Resources