How to create multiple connections in angular 6 using ngx-mqtt library? - javascript

I need to connect to multiple brokers from the same angular 6 app.
When importing MqttModule, we pass the config to it as:
imports: [...
MqttModule.forRoot(MQTT_SERVICE_OPTIONS),
...]
I tried creating 2 separate modules on same hierarchical level and passing different config and setting up the connections, but it is not working.
I think it creates services at the root level and we cannot create a separate connection in different modules.
Can we even create multiple connections? If so, how?

I tried so many things but the only thing work for me is below (Angular 8)
install following command in your project
npm i buffer --save
npm i -S process
npm i mqtt --save
Add following line to polyfills.js at the end
(window as any)['global'] = window;
global.Buffer = global.Buffer || require('buffer').Buffer;
import * as process from 'process';
window['process'] = process;
add following code to your app.component.ts
import { Component } from '#angular/core';
import * as mqttt from "mqtt";
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'checkMqttFromWeb';
constructor(){
var client = mqttt.connect('mqtt://192.168.0.29:1884')
client.on('connect', function () {
client.subscribe('fooBar', function (err) {
if (!err) {
client.publish('fooBar', 'Hello mqtt')
}
})
})
client.on('message', function (topic, message) {
// message is Buffer
console.log(message.toString())
client.end()
})
}
}
Now Run your app using ng serve
hope it's works

Related

How to access method of Project A into Project B in nodejs, i am using nestjs

i have MailEvent class and want to use SendEmail method in client project. i use NPM link to share code for client project. but i can't access this method. how can i access this method in client project. i am using nestJS framework. thanks
#Injectable()
export class MailEvent {
constructor(private eventEmitter: EventEmitter2) {}
// store email details to RabbitMQ
SendEmail() {
amqplib.connect(
'amqp://localhost',
(connectionError, connection) => {
if (connectionError) {
throw connectionError;
}
connection.createChannel((channelError, channel) => {
if (channelError) {
throw channelError;
}
const queue = 'Test_emails_queue';
channel.assertQueue(queue, { durable: false });
channel.sendToQueue(queue, Buffer.from(JSON.stringify(email)));
// create event for sending email
this.eventEmitter.emit('send_email', email);
});
},
);
}
In nestjs we can create a reusable module. Then, this module can be imported to another module. If the module is stored in separated repo, then we can build the module first before installing it to another repo using NPM.
Steps to do:
generate nestjs resource, e.g. MailEventModule on the terminal. It will also create the controller and service class
nest g resource mail-event
export the service via the module file mail-event.module.ts
import { Module } from '#nestjs/common';
import { MailEventService } from './mail-event.service';
#Module({
providers: [MailEventService],
exports: [MailEventService]
})
export class MailEventModule { }
Build the module. It will create a new folder named DIST containing the module ready to be installed in another repo/project
npm run build
upload the mail-event module to npm
install mail-event in the client project using npm command, e.g. npm install mail-event
Import the module to the client project in client-project.module.ts
import { Module } from '#nestjs/common';
import { MailEventModule } from 'mail-event';
#Module({
imports: [MailEventModule]
})
export class ClientProjectModule { }
Add MailEventService as dependency to the client project service in client-project.service.ts
import { Injectable } from '#nestjs/common';
import { MailEventService } from 'mail-event';
#Injectable()
export class ClientProjectService {
constructor(private mailEventService: MailEventService) { }
myFunction() {
this.mailEventService.sendEmail();
}
}
If you have tried this steps, please give us the feedback whether it works or not. Thank you

How to use Chrome Extension Api with Angular?

I am working on a chrome extension, I have a "background.js" which it filters the url and fetchs data from my api. When the conditions is meet I am sending a message from "background.js". And I want to catch it from Angular component.
background.js
...
chrome.pageAction.show(tab.id, () => {
chrome.runtime.sendMessage({data: dataFromAPI})
});
...
I ran npm install --save #types/chrome.
app.component.ts
import {Component} from '#angular/core';
import {chrome} from '#types/chrome';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor() {
chrome.runtime.onMessage.addListener( data => console.log(data));
}
}
But WebStorm says, ".../node_modules/#types/chrome/index.d.ts' is not a module. "
How can I use Chrome Api from Angular Component?
/// <reference types="chrome"/>
import {chrome} from '#types/chrome';
// Remove chrome import
IMPORTANT: Must add three slashes before reference.
If still it doesn't work then add "Chrome" in tsconfig.json types.
compilerOptions: ["types": [ "Chrome" ] ]
Add the line
///<reference types="chrome"/>
to the very top of your TS file (preferably line 1). (DO NOT OMIT THE 3 SLASHES IN THE BEGINNING)
Also run the command
npm install --save #types/chrome
Things will start working after that.
In my case, I installed npm install --save #types/chrome
so file stop showing an error Cannot find name 'chrome' when build
then I'm trying to build the library by using the command ng build but it was broken because it didn't find a chrome so what I did?
I added this line ///<reference types="chrome"/> on top of file public-api.ts
Note: Must add three slashes(///) before reference.

How to send 2 numbers from Angular, add them with Node.js and display the result back in Angular? (Only those 2... no databases, no libraries) [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I am new to Angular and Node.js. I know this must be very simple but I am having a hard time finding the answer with some sample code just by searching it in google (using Angular with Node.js) and find this solution being done with only Angular or only Node.js. I am trying to understand how Angular and Node.js work together. In YouTube I find tutorials of making a MEAN app (which ends up doing a CRUD with MongoDB), but in my case I don't want to use a database just plain Angular with Node.js.
To make things simple, I want 2 textboxes with a button in Angular that sends the 2 numbers to Node.js and adds them in Node.js. Then I want the answer to be sent back from Node.js to Angular and be displayed in another textbox in Angular.
How would I achieve this? Could I be provided with some code to understand? (I am trying to do something totally different from what I am asking, but it will help me to understand and make sense of how the Angular works with Node.js)
First, we write a simple http server using node:
const http = require('http');
const httpServer = http.createServer(requestHandler);
httpServer.listen(3000, () => {
console.log('Node.JS server is listening on port 3000')
});
function requestHandler(request, response){
console.log(`Request came: ${request.url}`);
if(request.url.startsWith('/add/')){
try{
let parts = request.url.substring(5).split('/')
let result = Number(parts[0]) + Number(parts[1])
response.writeHead(200, {'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*'});
response.write(result.toString());
response.end();
console.log(`Response: 200 ${request.url}`);
return;
}catch(e){
console.log(e);
}
}
response.writeHead(400);
response.write(`bad request '${request.url}' is not valid. example url: /add/5/7`);
response.end();
console.log("Response: 404 ${request.url}");
}
Save above code as server.js and run it using node server.js
Then create an angular project using ng new node-ng-test
Edit app.component.html like this:
<input type="number" #firstNumber>
<input type="number" #secondNumber>
<button (click)="callAddApi(firstNumber.value, secondNumber.value)">Add</button>
<p *ngIf="result"> {{firstNumber.value}} + {{secondNumber.value}} = {{result}}</p>
Also change app.component.ts as this:
import { Component } from '#angular/core';
import { HttpClient } from '#angular/common/http';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
result = undefined;
constructor(private http: HttpClient) { }
callAddApi(firstNumber, secondsNumber) {
this.http.get<any>(`http://localhost:3000/add/${firstNumber}/${secondsNumber}`)
.subscribe(r => this.result = r, e => console.log(e));
}
}
Don't forget to import HttpClientModule in app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { HttpClientModule } from '#angular/common/http';
import { AppComponent } from './app.component';
#NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Finally, run angular app using ng serve --open and try it!

ionic 2 with strophe not working?

I am currently trying to use strophe with ionic 2, I have npm both strophe and jquery and also #types/strophe and typings.
this is my code
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import {Strophe} from 'strophe';
#Component({
selector: 'page-home',
templateUrl: 'home.html',
})
export class HomePage {
public connection: any ;
public BOSH_SERVICE: any="http://52.32.***.5:5280/http-bind/" ;
constructor(public navCtrl: NavController) {
}
login() {
this.connection = new Strophe.Connection(this.BOSH_SERVICE);
this.connection.connect('ama****'+'#'+'localhost', 'o***oop', this.onConnect);
console.log("Hello World !");
}
onConnect(status) {
console.log('onConnect: '+status);
}
when I try ionic serve I get this error
TypeError: __WEBPACK_IMPORTED_MODULE_2_strophe__.Strophe is undefined
Stack trace:
HomePage.prototype.login#http://localhost:8100/build/main.js:55747:9
View_HomePage_0/<#ng:///AppModule/HomePage.ngfactory.js:135:21
viewDef/handleEvent#http://localhost:8100/build/main.js:12170:98
callWithDebugContext#http://localhost:8100/build/main.js:13462:39
debugHandleEvent#http://localhost:8100/build/main.js:13050:12
dispatchEvent#http://localhost:8100/build/main.js:9070:12
renderEventHandlerClosure/<#http://localhost:8100/build/main.js:9662:20
decoratePreventDefault/<#http://localhost:8100/build/main.js:33505:53
f</t.prototype.invokeTask#http://localhost:8100/build/polyfills.js:3:9644
NgZone.prototype.forkInnerZoneWithAngularBehavior/this.inner<.onInvokeTask#htt p://localhost:8100/build/main.js:4397:28
f</t.prototype.invokeTask#http://localhost:8100/build/polyfills.js:3:9557
c</r.prototype.runTask#http://localhost:8100/build/polyfills.js:3:4812
t/this.invoke#http://localhost:8100/build/polyfills.js:3:10626
1) download Strophe library from Strophe Site
Then, You should put the framework inside /src/assets/
Then, You should add the script tag to the index.html before polyfills.js and main.js
Thus
<script src="assets/strophejs-1.2.14/strophe.js"></script>
Last,
you should put this declare statement before to use the strophe.
declare var Strophe: any;
It works for me!
2) another way is you can install using
npm install strophe.js
and copy strophe.js file from node_modules/strophe.js folder to your src/assets folder as above and then give path in your index file

How to include external JavaScript libraries in Angular 2?

I am trying to include an external JS library in my Angular 2 app and trying to make all the methods in that JS file as a service in Angular 2 app.
For eg: lets say my JS file contains.
var hello = {
helloworld : function(){
console.log('helloworld');
},
gmorning : function(){
console.log('good morning');
}
}
So I am trying to use this JS file and reuse all the methods in this object and add it to a service, so that my service has public methods, which in turn calls this JS methods. I am trying to reuse the code, without reimplementing all the methods in my typescript based Angular 2 app. I am dependent on an external library, which I cant modify.
Please help, thank you in advance.
With ES6, you could export your variable:
export var hello = {
(...)
};
and import it like this into another module:
import {hello} from './hello-module';
assuming that the first module is located into the hello-module.js file and in the same folder than the second one. It's not necessary to have them in the same folder (you can do something like that: import {hello} from '../folder/hello-module';). What is important is that the folder is correctly handled by SystemJS (for example with the configuration in the packages block).
When using external libs which are loaded into the browser externally (e.g. by the index.html) you just need to say your services/component that it is defined via "declare" and then just use it. For example I recently used socket.io in my angular2 component:
import { Component, Input, Observable, AfterContentInit } from angular2/angular2';
import { Http } from 'angular2/http';
//needed to use socket.io! io is globally known by the browser!
declare var io:any;
#Component({
selector: 'my-weather-cmp',
template: `...`
})
export class WeatherComp implements AfterContentInit{
//the socket.io connection
public weather:any;
//the temperature stream as Observable
public temperature:Observable<number>;
//#Input() isn't set yet
constructor(public http: Http) {
const BASE_URL = 'ws://'+location.hostname+':'+location.port;
this.weather = io(BASE_URL+'/weather');
//log any messages from the message event of socket.io
this.weather.on('message', (data:any) =>{
console.log(data);
});
}
//#Input() is set now!
ngAfterContentInit():void {
//add Observable
this.temperature = Observable.fromEvent(this.weather, this.city);
}
}

Categories

Resources