node-forge import in angular 2 service - node.js

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;

Related

How to fix "× TypeError: Object(...) is not a function"?

I'm making a netflix clone app in nodejs and got stuck on generateMedia function.
On TabContentOne.js file, On import { generateMedia } from 'react-media-query' it is dotted and when I run npm install #types/react-media-query it gives me errors. I did npm i react-media-query.
import React from 'react';
import styled from 'styled-components';
import { Button } from './Button';
import { generateMedia } from 'react-media-query'
// Media Query
const customMedia = generateMedia({
smDesktop: '1440px',
tablet: '960px'
})
This is the link from my bitbucket https://bitbucket.org/danclaudiu95/nodejs-reactjs.git
I'm expecting to use generateMedia function the put style on some elements in my application but the npm server doesn't start anymore.
I recommend using another package that does the same thing, "react-media-query" is outdated and removed from github.

Angular6 :Property catch does not exist

I am new to Angular and I have basic knowledge of it. I want to learn HttpClient so I can create a json file instead of real server. I created a service and imported HttpClient:
service.ts
import { Injectable } from '#angular/core';
import {HttpClient, HttpErrorResponse} from '#angular/common/http';
import {IEmployee} from "../../../service/src/app/employee";
import {Observable} from "rxjs/index";
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
In my class EmployeeService I have created a method for getting data from json file:
#Injectable({
providedIn: 'root'
})
export class EmployeeService {
private _url: string = "/assets/data/employees.json";
constructor(private http:HttpClient) { }
getEmployee():Observable<IEmployee[]> {
return this.http.get<IEmployee[]>(this._url)
.catch(this.errorHandler);
}
errorHandler(error: HttpErrorResponse) {
return Observable.throw(error.message || "Server Error")
}
}
But in getEmployee method I got these errors:
ERROR in ./src/app/employee.service.ts
Module not found: Error: Can't resolve 'rxjs/add/observable/throw' in 'E:\Tutorial\NodeJS\WebstormProjects\Angular\http\src\app'
ERROR in ./src/app/employee.service.ts
Module not found: Error: Can't resolve 'rxjs/add/operator/catch' in 'E:\Tutorial\NodeJS\WebstormProjects\Angular\http\src\app'
i 「wdm」: Failed to compile.
As you can see I have imported throw and catch operator but I do not know why I keep getting errors.
The other problem is, below throw method appear a line because of deprecated(Deprecated symbol used, consult docs for better alternative)!!
What is the alternative?
Angular CLI: 6.0.1
Node: 10.0.0
OS: win32 x64
Angular:
...
Package Version
------------------------------------------------------
#angular-devkit/architect 0.6.1
#angular-devkit/core 0.6.1
#angular-devkit/schematics 0.6.1
#schematics/angular 0.6.1
#schematics/update 0.6.1
rxjs 6.1.0
typescript 2.7.2
****************** EDIT ***************
I want to use builtin Observable in Angular yet and i do not want to use RXJS third party lib for angular.
This is my node module rx folder and you can see observable file in it.
And in node_modules\rxjs\operator folder there are throw and catch file..
But why it wants to search these files into E:\Tutorial\NodeJS\WebstormProjects\Angular\http\src\app folder that is make a error?
I fixed my problem by installing :
npm install --save rxjs#6 rxjs-compat#6
and use this path for rxjs:
import {Observable, Subject, asapScheduler, pipe, of, from, interval, merge, fromEvent, throwError} from 'rxjs';
import {catchError} from "rxjs/internal/operators";
Seems catch depricated at angular 6 so in order to i have used catchError like below :
getEmployee():Observable<IEmployee[]> {
return this.http.get<IEmployee[]>(this._url)
.pipe(
catchError(this.errorHandler));
}
errorHandler(error: HttpErrorResponse) {
return throwError(error.message || "Server Error")
}
And all errors gone now :-)
These below references are enough for you. remove unwanted references
import { Injectable } from '#angular/core';
import {HttpClient, HttpErrorResponse} from '#angular/common/http';
import {IEmployee} from "../../../service/src/app/employee";
import {Observable} from "rxjs/Observable";
Where,
removed these below references
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
And changed "rxjs/Observable" ainstead of "rxjs/index";
Update:
Should check your rxjs folder having these files, if not, then your package has missed something. you need re-install it.
Import these References
import { throwError, Observable } from 'rxjs';
import {throwError as observableThrowError} from 'rxjs';
import {catchError} from 'rxjs/operators'
and then change your code below as
getEmployees():Observable<IEmployee[]> {
return this.http.get<IEmployee[]>(this._url).pipe(
catchError(this.errorHandler));
}
errorHandler(error: HttpErrorResponse) {
return observableThrowError(error.message ||"server error");
}
https://www.youtube.com/watch?v=ScaKGrW5s0I&list=PLC3y8-rFHvwhBRAgFinJR8KHIrCdTkZcZ&index=31
if you still not understand check above video link
ErrorObservable creates an Observable that emits no items to the Observer and immediately emits an error notification.
Just import like this
import { ErrorObservable } from 'rxjs/observable/ErrorObservable';
And create error
ErrorObservable.create('error');

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.

Cannot find module './lib/BufferMaker' when use buffermaker in Meteor 1.5.1

I have encountered a problem when use some npm package in Meteor (version 1.5.1), any help on it will be much appreciated.
My Environment:
meteor: 1.5.1
buffermaker: 1.2.0
What I Did:
Create a sample Meteor app.
meteor create test
Install buffermaker
meteor npm install --save buffermaker
Import buffermaker in Meteor app by editing test/client/main.js, add line:
import { BufferMaker } from 'buffermaker';
Full content of test/client/main.js:
import { Template } from 'meteor/templating';
import { ReactiveVar } from 'meteor/reactive-var';
import { BufferMaker } from 'buffermaker';
import './main.html';
Template.hello.onCreated(function helloOnCreated() {
// counter starts at 0
this.counter = new ReactiveVar(0);
});
Template.hello.helpers({
counter() {
return Template.instance().counter.get();
},
});
Template.hello.events({
'click button'(event, instance) {
// increment the counter when button is clicked
instance.counter.set(instance.counter.get() + 1);
},
});
Run the Meteor app
meteor npm install
meteor
I got this error in the console of browser (Chrome).
modules-runtime.js?hash=8587d18…:231 Uncaught Error: Cannot find module './lib/BufferMaker'
at makeMissingError (modules-runtime.js?hash=8587d18…:231)
at require (modules-runtime.js?hash=8587d18…:241)
at index.js (modules.js?hash=e9fc8db…:1016)
at fileEvaluate (modules-runtime.js?hash=8587d18…:343)
at require (modules-runtime.js?hash=8587d18…:238)
at main.js (main.js:1)
at fileEvaluate (modules-runtime.js?hash=8587d18…:343)
at require (modules-runtime.js?hash=8587d18…:238)
at app.js?hash=3f48780…:101
Did you try:
import BufferMaker from 'buffermaker';
Some if not most modules do a default export meaning that you don't need the curley braces in your import statement
Turns out buffermaker re-exports it’s main module in a strange way, so first step is to bypass it by importing BufferMaker directly:
import BufferMaker from 'buffermaker/lib/BufferMaker';
Then you’ll find when you call .make(), it will complain about Buffer not existing. To get Buffer on the client, first install meteor-node-stubs
$ meteor npm install --save meteor-node-stubs
Then load the buffer module and stick it on the window so BufferMaker can access it
import { Buffer } from 'buffer';
window.Buffer = Buffer;
/* OR do it with require */
window.Buffer = require('buffer').Buffer;

Angular 2 - Import html2canvas

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);
})

Resources