How to use node.js module with Angular 6? - node.js

I am newbie in Angular 6 and TypeScript. Can someone show me the right way to use node.js third-party module in Angular 6?
For example i want to create component with ability to consume and make requests to SOAP wsdl methods.
Did installed it by adding to package.json with npm install.
Trying to use node-soap npm module like this:
import { Injectable } from '#angular/core';
import * as soap from 'node-soap';
#Injectable({
providedIn: 'root'
})
export class MySoapService {
constructor() { }
getOrderInfo() {
const url = 'http://my-example-api.com/WCF/ClientService.svc?singleWsdl';
let args = {
login: 'login',
password: 'password',
orderNumber: 'F976638'
};
soap.createClient(url, function(err, client) {
client.GetOrderInfo(args, function(err, result) {
console.log(result);
});
});
};
}
Then inject this service into component and render it, just to test the service...
But got some error during ng serve:
ERROR in ./node_modules/node-soap/client.js
Module not found: Error: Can't resolve 'http' in '/home/cadistortion/WebstormProjects/my-ng-app/node_modules/node-soap'
Thank you!

it's easy, in your url have your API node.
You go need more, express.js(or other) for get work.
BD - like MongoDB or other or Json.
See this vídeo and other the same user https://www.youtube.com/watch?v=M-G48Gf2Xl0
is complete how create blog using MEAN Stack

Related

Adminjs ComponentLoader not found

I have been trying to make custom component in Adminjs 6.6.5 dashboard but Adminjs ComponentLoader not found error occurs. then i have tried to
import AdminJS from 'adminjs'
const {ComponentLoader} = AdminJS
but i get: Trying to bundle file 'file:/Users/Josip/WebstormProjects/ferry-backend/components/dashboard.jsx' but it doesn't exist
I would really appreciate help...
admin/index.js
import {ComponentLoader} from "adminjs";
const componentLoader = new ComponentLoader()
const Components = {
MyDashboard: componentLoader.override('Dashboard','../components/dashboard.jsx')
}
export { componentLoader, Components }
index.js
import {componentLoader, Components} from "./admin/index.js";
AdminJS.registerAdapter(AdminJSSequelize)
const admin = new AdminJS({
databases: [],
rootPath: '/admin',
resources:[UsersResources, GuestResources, SalesResources, FinancesResources],
components:{
edit: Components.MyDashboard
},
componentLoader
})
you are fixed this problem? I also ran into this problem and don't understand how to solve it
i fixed this problem. You need to do the import as follows
import AdminJs from 'adminjs';
// And now you can use any adminjs dependencies as follows
AdminJs.ValidationError(errors)
My usage example:
if(Object.keys(errors).length) {throw new AdminJs.ValidationError(errors)} else {...}
Good luck with your development!

Problem using a npm package in React - says "TypeError: require is not a function"

I'm trying to use the package lastfm within a React app.
I have installed it with
npm install lastfm
The official doc says it should be used like this :
var LastFmNode = require('lastfm').LastFmNode;
var lastfm = new LastFmNode({
api_key: 'abc',
secret: 'secret'
});
And this is how I use it in my React code :
import {LASTFM_API,LASTFM_API_SECRET} from "./Constants";
import {LastFmNode} from 'lastfm';
export class Lastfm {
static scrobbleTrack(track): void {
var lastfm = new LastFmNode({
api_key: LASTFM_API,
secret: LASTFM_API_SECRET,
useragent: 'appname/vX.X MyApp'
});
}
}
Which fires this error (from the package) :
TypeError: require is not a function at lastfm-request.js:3
I'm quite new to React and NPM.
I wonder if there is some kind of incompatibility ?
How could I make this work ?
Thanks !
The package is to be used on Node server and not on React App.
EDIT
Hi, sorry i cannot comment because my points are less.
You can not use that one as well because that is also a node package. If you see a syntax where you have to use: require('something'); usually means it is a node package because in React, your syntax for importing is something like this: const abc from 'xyz';

Angular9 http.get() doesn´t work properly

i'm developing a simple app to make consults to a backend on NodeJS. Everything works perfectly on localhost, but when i run the angular server on my ip adress (192.168.1.x) it dosen`t work anymore.
The nodeJS REST api it's running on 'http://localhost:3000/api/article' and the Angular server in https://192.168.1.x:4200.
The http.get code its this:
articles.component.ts:
import {ArticlesService} from '../../services/articles.service';
import {Article} from '../../models/article';
import { ViewChild } from '#angular/core'
#Component({
selector: 'app-articles',
templateUrl: './articles.component.html',
styleUrls: ['./articles.component.scss'],
providers: [ArticlesService],
})
export class ArticlesComponent implements OnInit {
constructor(public articlesService: ArticlesService) { }
article: Article;
//Some other code that dosen't afect this
getArticle(id: String) {
this.articlesService.getArticle(id)
.subscribe( res => {
this.article = res as Article;
})
}
articles.service.ts:
import { HttpClient } from '#angular/common/http';
#Injectable({
providedIn: 'root'
})
export class ArticlesService {
readonly API_URI = 'http://localhost:3000/api/article';
constructor(private http: HttpClient) {
}
getArticle(id: String) {
return this.http.get(this.API_URI+`/${id}`);
}
}
I`ve been trying some flags test and i realize that it never enter on the subscribe(), i'm new and it's the first time i run the server on my current ip and not in the localhost. So, i don't if maybe i can't request at the backend like that in this case or something else.
Using morgan and postman at the nodeJS REST api i see that the get request work properly on that side.
If someone could help me it would be awsome.
I exactly don't get you with the Angular server but all indicates that your Angular server doesn't have visibility of your localhost:3000. It's like when you deploy your spa in another server. That server doesnt know about your localhost and you have to replace your API_URI (using environments.ts) with the IP or domain name where your backend is:
For example i have this in my environment.prod.ts:
export const environment = {
production: true,
apiUrl: 'https://urltothenodejsbackend/api',
apiVersion: '/v1'
};

Can we use all node npm packages in Nestjs

In current, I am learning Nestjs, I found that Nestjs have a list of its own npm package like #nestjs/cqrs, #nestjs/jwt etc. Full list of all packages is https://www.npmjs.com/org/nestjs.
Now I have a doubt that can we use all npm packages in nestjs that we use in any Node.js application like morgan, windston etc.
Or we can only use the packages that mention in nestjs documentation list.
First, node.js packages can be used in Nestjs with its custom provider. So see the current docs.
Second, Brunner on the Nestjs core team helped me with this on the Nestjs_framework Reddit. He made a nice brief example for us on Github. I asked him to change the name from reddit to node so that will break this link, but you can find it on his Github site. He deserves the credit.
We aren't supposed to link to a solution on SO. So let's get started.
Brunner changed my architecture and I like his approach. I wanted to use the Cloudinary Node SDK which doesn't have a Nestjs module. This should work for importing any Node package, at least that is my understanding.
Note: When you write this.cloudinary. you expect to see a list of methods after that '.' . You won't, so just use whatever code the SDK or package docs tells you to use. A little weirdness.
The Cloudinary components live in a folder inside my members directory, which has a bunch of modules imported into it.
cloudinary.module.ts
import { Module } from '#nestjs/common';
import { cloudinaryProvider } from './cloudinary.provider';
import { CloudinaryService } from './cloudinary.service';
#Module({
providers: [cloudinaryProvider, CloudinaryService],
exports: [cloudinaryProvider],
})
export class CloudinaryModule {}
cloudinary.provider.ts
import { Provider } from '#nestjs/common';
import * as CloudinaryLib from 'cloudinary';
export const Cloudinary = 'lib:cloudinary';
export const cloudinaryProvider: Provider = {
provide: Cloudinary,
useValue: CloudinaryLib,
};
cloudinary.service.ts
import { Injectable, Inject } from '#nestjs/common';
import { Cloudinary } from './cloudinary.provider';
#Injectable()
export class CloudinaryService {
constructor(
#Inject(Cloudinary) private cloudinary
) {
// console.log('This is the cloudinary instance:');
// console.log(this.cloudinary);
}
}
And finally the parent module:
members.module.ts
import { CloudinaryModule } from './cloudinary/cloudinary.module'
#Module({
imports: [
CloudinaryModule,
...
Nest will expose the http adapter so that you can hook into it, here is an example using the morgan & body-parser npm package:
import { NestFactory } from '#nestjs/core';
import { AppModule } from './app.module';
import { ConfigService } from './config/config.service';
import { ConfigModule } from './config/config.module';
import bodyParser from 'body-parser';
import morgan from 'morgan';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
const configService = app.select(ConfigModule).get(ConfigService);
app.use(bodyParser.json());
app.use(morgan('dev'));
app.enableCors();
await app.listen(configService.PORT, () => console.log(`Server listening on port ${configService.PORT}`));
}
bootstrap();
In this instance above appis an express instance.
Nest is a framework that runs on top of an HTTP adapter (the main two that I know of being Fastify and Express with Express being the default adapter). If the package you are wanting to work with works with express (such as Morgan) then it's no problem. If the package you are wanting to use is platform agnostic (like Pino or Winston) then there are no problems. If the package you want to use is for a different HTTP adapter (like koa-router) then you have a problem (the counter example being something like #hapi/joi which is maintained by the hapi framework maintainers, but is actually adaptable to work with anything). There are some typescript specific packages class-validator and class-transformer come to mind, but overall if the package works on any node environment, it can work for Nest. If you have any questions about packages and implementation you could always check out the discord and ask your question there.

App Object in Electron Module and getAppPath throws Error

I have a strange problem with my application. I get an error, and I can't solve it. First at all, I installed a new project, so everything is clean. Someone sent me this repo to use for an Angular, Electron and Nodejs Application. Everything worked fine, but then I decided to install an embedded database like sqlite3. For this I found NeDB, and the module is perfect for my needs. First I had the problem, has nothing to do with my general problem, that I can't create a database file. So I read that I can only create files in my application path, because something about Electron and that's working in a browser.
I found the getAppPath() method that is implemented in my app object from the Electron module. Here starts the problem. For hours I tried to get the application path from this object. Finally, I wrote this code.
import { Injectable } from '#angular/core';
var nedb = require('nedb');
import { app } from 'electron';
import * as path from 'path';
#Injectable()
export class DatabaseService {
app: typeof app;
Database: any;
constructor() {
this.app = window.require("electron").app;
this.Database = new nedb({ filename: path.join(this.app.getAppPath(), '/diary.db'), autoload: true, timestampData: true });
var scott = {
name: 'Scott',
twitter: '#ScottWRobinson'
};
this.Database.insert(scott, function(err, doc) {
console.log('Inserted', doc.name, 'with ID', doc._id);
});
}
}
And I get this error.
I found this posting, but I don't really understand what the post is trying to tell me. I followed the links, but nothing seems to help. Anyone have an idea?

Resources