Unable to connect to a C# Socket using Angular - javascript

I'm trying to connect to a Socket from my angular Application on the ngOnInit method.
Here is how my Service Looks Like
import { Injectable } from '#angular/core';
import {webSocket, WebSocketSubject} from 'rxjs/webSocket';
import { map } from 'rxjs';
#Injectable({
providedIn: 'root'
})
export class SocketService {
private socket$!: WebSocketSubject<any>;
constructor() {
// Connect to the local websocket server on port 15001. Handle any Exceptions.
try {
this.socket$ = webSocket('ws://localhost:15001');
}
catch (e) {
console.log(e);
}
}
// Receive messages from the server
public receive(){
return this.socket$.pipe(
map(message=>JSON.parse(message))
)
}
}
Here is My Component.ts
import { Component, OnInit } from '#angular/core';
import { SocketService } from './services/socket.service';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
constructor(private socketService: SocketService) { }
ngOnInit() {
try{
this.socketService.receive().subscribe((data) => {
console.log(data);
});
}
catch (e) {
console.log(e);
}
}
title = 'MarketFeed';
}
Despite adding a try-catch I'm getting this error which is difficult to debug.
Here is the Error Message on the console
WebSocket connection to 'ws://localhost:15001/' failed:
ngOnInit # app.component.ts:15 Show 37 more frames app.component.ts:15
ERROR Event {isTrusted: true, type: 'error', target: WebSocket,
currentTarget: WebSocket, eventPhase: 0, …} Zone -
WebSocket.addEventListener:error (async)
ngOnInit # app.component.ts:15 Promise.then (async) 4431 # main.ts:6
webpack_exec # main.ts:7 (anonymous) # main.ts:7 (anonymous) # main.ts:7 (anonymous) # main.js:2 Show 134 more frames
Blockquote
What could I be missing? I'm able to consume the same socket using node js. But here on Angular, it is not working.

Related

Having issues updating legacy Angular project use old HTTP to new HTTPClient for basic auth

This is in an Angular 7 project and the code was written maybe 5-6 years ago, and I'm trying to update the application to latest Angular. Right now I'm just testing the login portion of the app which is basic http authentication. This is the last piece I need to refactor but im pretty lost. I don't want to break the entire system or do a full revamp just get something working so the whole ui can be upgraded from angular 7 to 14.
This is the old code below.
import { ConnectionBackend, Http, Request, RequestOptions, RequestOptionsArgs, Response, XHRBackend } from '#angular/http';
import { AuthService } from './../auth/auth.service';
import { Injectable } from '#angular/core';
import { Observable } from 'rxjs';
#Injectable()
export class AuthHttp extends Http {
constructor(backend: XHRBackend, defaultOptions: RequestOptions, private auth : AuthService) {
super(backend, defaultOptions);
this.auth = auth;
}
request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
// hack to deal with compatibility issue of rxjs versions
// see https://stackoverflow.com/questions/38168581/observablet-is-not-a-class-derived-from-observablet
let optionsAny = <any>options;
let opts: RequestOptionsArgs = {
method: optionsAny.method,
body: optionsAny.body,
withCredentials: true,
headers: optionsAny.headers,
}
let query = '';
for (let k of Array.from(optionsAny.params.paramsMap.keys())) {
let v = optionsAny.params.paramsMap.get(k);
query += '&' + k + '=' + encodeURIComponent(v);
}
if (query) {
url = url + '?' + query.substring(1);
}
return Observable.create(sub => {
super.request(url, opts).subscribe(
res => { sub.next(res); },
err => {
if (err.status === 401) {
this.auth.signout();
} else {
sub.error(err);
}
} );
});
}
}
I tried some stuff but it all seems to lead to no where. I'm not really sure where to start. This is my first time using angular and it's a decently sized project. I feel like there's a really simple way to do this, but I'm not totally sure, I've been researching and haven't found anyone quite doing anything like this.
It compiles with no errors with an empty class. Like below, these imports are all the equivalent or roughly equivalent for the new angular httpclientmodule I believe .
import { AuthService } from './../auth/auth.service';
import { Injectable } from '#angular/core';
import { Observable } from 'rxjs';
import { HttpClient, HttpParams, HttpHeaders, HttpXhrBackend, HttpResponse, HttpBackend, HttpRequest, HttpEvent } from '#angular/common/http';
#Injectable()
export class AuthHttp extends HttpClient {}
Then I get 2 errors below in the console of my browser when i do ng serve with the blank class above.
ERROR NullInjectorError: R3InjectorError(AppModule)[ApiService -> ApiService -> ApiService]:
NullInjectorError: No provider for ApiService!
Angular 9
AppComponent_Factory app.component.ts:11
Angular 26
631 main.ts:11
Webpack 7
core.mjs:6362:22
Angular 16
Any help on where to start or helpful resource is appreciated thank you.
This is how ApiService is implemented
#Injectable()
export class ApiService {
private apiUrl: string;
constructor(private authHttp: AuthHttp, private auth: AuthService) {}
getUrl() {
return this.apiUrl;
}
setUrl(url: string) {
this.apiUrl = url;
}
getConfiguration(): Configuration {
const token = this.auth.getToken();
return new Configuration({
accessToken: token
});
}
getUserApi(): UserService {
return new UserService(this.authHttp, this.apiUrl, this.getConfiguration());
}
getProductionApi(): ProductionService {
return new ProductionService(
this.authHttp,
this.apiUrl,
this.getConfiguration()
);
}
Without seeing the implementation of ApiService and its difficult to identify the issue. Broadly speaking it seems to me like the ApiService isn't provided from any module.
A quick check would be to provide it to the root of the application.
#Injectable({
providedIn: 'root',
})
export class ApiService ....
Ok I got it working but I'm still not totally sure how it's working or what it's doing. Basically the old method was doing this in a complicated why because of the limitations of older angular 2.
#Injectable()
export class AuthHttp extends HttpClient implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const authReq = req.clone({
withCredentials: true
});
return next.handle(authReq);
}
}

Angular 14 - Uncaught (in promise): NullInjectorError: R3InjectorError(Standalone[z])[s -> s -> s]:

I tried to update my project from angular 13 to angular 14, when I serve this app there is no error occures in CLI and the route work for only default path but when I try to navigate to another page it causes this error,
Also there is no NgModule present, I deleted all the modules from my project after making standlone component.
ERROR Error: Uncaught (in promise): NullInjectorError: R3InjectorError(Standalone[u])[s -> s -> s]:
NullInjectorError: No provider for s!
NullInjectorError: R3InjectorError(Standalone[u])[s -> s -> s]:
NullInjectorError: No provider for s!
at Vf.get (core.mjs:9131:27)
at Bf.get (core.mjs:9298:33)
at Bf.get (core.mjs:9298:33)
at Bf.get (core.mjs:9298:33)
at J0.get (core.mjs:22219:36)
at Io (core.mjs:3378:39)
at Cs (core.mjs:3423:12)
at Object.Fi (core.mjs:10447:12)
at e.ɵfac [as factory] (info.component.ts:18:27)
at er (core.mjs:3608:44)
at Me (zone.js:1211:31)
at Me (zone.js:1165:17)
at zone.js:1278:17
at F.invokeTask (zone.js:406:31)
at Object.onInvokeTask (core.mjs:26490:33)
at F.invokeTask (zone.js:405:60)
at pe.runTask (zone.js:178:47)
at D (zone.js:585:35)
Mv # core.mjs:6751
handleError # core.mjs:6798
next # core.mjs:27035
next # Subscriber.js:91
_next # Subscriber.js:60
next # Subscriber.js:31
(anonymous) # Subject.js:34
ne # errorContext.js:19
next # Subject.js:27
emit # core.mjs:23126
(anonymous) # core.mjs:26529
invoke # zone.js:372
run # zone.js:134
runOutsideAngular # core.mjs:26402
onHandleError # core.mjs:26529
handleError # zone.js:376
runGuarded # zone.js:147
l.microtaskDrainDone # zone.js:1072
D # zone.js:592
Promise.then (async)
Ne # zone.js:561
X # zone.js:572
scheduleTask # zone.js:396
onScheduleTask # zone.js:283
scheduleTask # zone.js:386
scheduleTask # zone.js:221
scheduleMicroTask # zone.js:241
Be # zone.js:1265
Me # zone.js:1202
(anonymous) # zone.js:1118
n # jsonp chunk loading:77
(anonymous) # src_app_info_info_component_ts.js:1
index.js:551
I'm wonder because then how it serve the default path but not any other path.
Here is my app.routing-module.ts file seems like :
import { Routes } from '#angular/router';
export const routes: Routes = [
{
path: 'home',
loadComponent: () => import('./home//home.component').then((m) => m.HomeComponent),
title: 'Sefat Anam - Home Page'
},
{
path: 'portfolio',
loadComponent: () => import('./info/info.component').then((m) => m.InfoComponent),
title: 'Sefat Anam - Portfolio Page'
},
{
path: 'art',
loadComponent: () => import('./art/art.component').then((m) => m.ArtComponent),
title: 'Sefat Anam - Art Page'
},
{
path: '',
redirectTo: 'home',
pathMatch: 'full'
}
];
Here the the component which occure error & also other component are same as it,
#Component({
selector: 'app-info',
templateUrl: './info.component.html',
styleUrls: ['./info.component.scss'],
standalone: true,
providers: [CommonModule,HttpClientModule]
})
export class InfoComponent implements OnInit {
technologies!: Observable<Technology[]>;
employmentHistories!: Observable<EmploymentHistory[]>;
educations!: Observable<Education[]>;
constructor(private httpClient: HttpClient) { }
ngOnInit(): void {
this.technologies = this.httpClient.get<Technology[]>(environment.api_url + 'technologies.json');
this.educations = this.httpClient.get<Education[]>(environment.api_url + 'educations.json');
this.employmentHistories = this.httpClient.get<EmploymentHistory[]>(
environment.api_url + 'employmentHistory.json'
);
}
and the main.ts file is like this,
if (environment.production) {
enableProdMode();
}
bootstrapApplication(AppComponent, {
providers: [
importProvidersFrom(RouterModule.forRoot(routes)),
]
}).catch(err => console.log(err))
What would be the issue or did I miss something ?
You should add CommonModule and HttpClientModule inside imports array not providers.
Try this:
#Component({
selector: 'app-info',
templateUrl: './info.component.html',
styleUrls: ['./info.component.scss'],
standalone: true,
imports: [CommonModule,HttpClientModule]
})
export class InfoComponent implements OnInit {
technologies!: Observable<Technology[]>;
employmentHistories!: Observable<EmploymentHistory[]>;
educations!: Observable<Education[]>;
constructor(private httpClient: HttpClient) { }
ngOnInit(): void {
this.technologies = this.httpClient.get<Technology[]>(environment.api_url + 'technologies.json');
this.educations = this.httpClient.get<Education[]>(environment.api_url + 'educations.json');
this.employmentHistories = this.httpClient.get<EmploymentHistory[]>(
environment.api_url + 'employmentHistory.json'
);
}

Nestjs cronjob cannot read inject service

I set up a cronjob that is supposed to fire and call a service from another module. console logged items are displaying in the console and When I run the method manually from the endpoint. The service returns a successful result. But once I put back the cronjob decorator. The service is undefined
throwing exception TypeError: Cannot read property 'getAll' of undefined
I have used other nodejs cronjob packages, but the error persists. Is there a workaround?
#Cron(CronExpression.EVERY_10_SECONDS)
async test() {
try {
console.log('working 22');
const ee = await this.Service.getAll();
console.log(ee);
for (const key in ee) {
console.log(ee[key].termsID);
}
const terms = await this.termsModel.find({
isDeleted: false
});
console.log(terms);
console.log('working 22 end!');
} catch (error) {
console.log(error)
}
}
appmodule
#Module({
imports: [
TermsModule,
ScheduleModule.forRoot()
],
controllers: [],
providers: [],
})
export class AppModule { }
You need to make sure that you declare the service that you want to use from the global module in the Cron-Service's providers. Consider this simple example:
// Sample Cron-Service
// -------------
#Injectable()
export class CronService {
private readonly logger = new Logger(CronService.name);
constructor(private globalService: GlobalService) {
}
#Cron(CronExpression.EVERY_5_SECONDS)
test() {
this.logger.debug(`Called every 5 seconds with random value: ${this.globalService.getSomeData()}`);
}
}
// Cron-Module
// -------------
#Module({
providers: [CronService, GlobalService] // <--- this is important, you need to add GlobalService as a provider here
})
export class CronModule {
}
// Global-Service
// -------------
#Injectable()
export class GlobalService {
getSomeData() {
return Math.random() * 500;
}
}
// Global-Module
// -------------
#Global()
#Module({
providers: [GlobalService]
})
export class GlobalModule {
}
Also, you need to make sure that the global module is imported in your root/core module - along with the ScheduleModule from the #nestjs/schedule package, e.g.:
#Module({
imports: [GlobalModule, ScheduleModule.forRoot(), ... ]
})
export class AppModule {
}

MQTT works only in one device

I've made an Ionic PWA mqtt that publishes via a websocket, but when I deploy the app (I'm using AWS), it only works in Google Chrome, if I test it in an Incognito window, it doesn't work.
In the console it show this error on all devices (pc/mobile) that aren't working:
bSocket connection to 'ws://test.mosquitto.org:8081/' failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET
Below is my javascript Ionic code
import { Component } from '#angular/core';
import { MQTTService } from 'ionic-mqtt';
#Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage {
private _mqttClient: any;
temp = 19;
private MQTT_CONFIG: {
host: string,
port: number,
clientId: string,
path: string,
} = {
host: "test.mosquitto.org",
port: 8081,
clientId: "qeekljeqe" + Math.floor(Math.random()*100),
path: "/",
};
private TOPIC: string[] = [];
constructor(private _mqttService: MQTTService) {
}
ngOnInit() {
this._mqttClient = this._mqttService.loadingMqtt(this._onConnectionLost, this._onMessageArrived, this.TOPIC, this.MQTT_CONFIG);
}
private _onConnectionLost(responseObject) {
// connection listener
// ...do actions when connection lost
console.log('_onConnectionLost', responseObject);
}
private _onMessageArrived(message) {
// message listener
// ...do actions with arriving message
console.log('message', message);
}
public publishMessage(TOPICO : string, VALOR : string) {
console.log('publishMessage')
this._mqttService.publishMessage(TOPICO, VALOR);
}

Http not working in Angular 2

I have some issue with my angular 2 project Http, I have set it in constructor as a parameter and inside the constructor it print as an undefined, bellow is the code from my project:
import 'rxjs/add/operator/toPromise';
import {Http, HttpModule, RequestOptions, XHRBackend} from "#angular/http";
import { Injectable } from '#angular/core';
#Injectable()
export class GetDataService{
private dataUrl = '/data'; // URL to web API
private req;
//mode = 'observable';
public headers;
public options;
constructor(http:Http) {
//this.http = new Http(XHRBackend, RequestOptions);
console.log(http);
}
}
here is my Error
EXCEPTION: Uncaught (in promise): Error: Error in
http://localhost:3000/app/invoice.component.html:160:0 caused by:
Cannot read property 'get' of undefined
Component where Service used
import {Component} from '#angular/core';
import {GetDataService} from "./get-data.service";
#Component({
selector: 'http',
template: `<h4>response</h4>`
})
export class GetDataComponent {
response:string;
getDataService:GetDataService;
constructor(){
this.getDataService = new GetDataService();
console.log(this.getDataService.getData());
}
}
and add service in main module providers
Also when I try to inject GetDataService in constructor parameter
constructor(getDataService:GetDataService){
this.getDataService = getDataService;
console.log(this.getDataService.getData());
}
I get --
Error: (SystemJS) Can't resolve all parameters for GetDataComponent
I have also tried to create object of Http inside constructor, but again I am getting error.
constructor() {
this.http = new Http;
console.log(this.http);
}
this is the result of above code:
Http {_backend: undefined, _defaultOptions: undefined}
Can anyone please help me.
Http is not supposed to be created with new Http().
Add HttpModule to your #NgModule({ imports: [BrowserModule, HttpModule], ...}) and inject Http using the constructor as shown in your first example.
For more details see https://angular.io/docs/ts/latest/tutorial/toh-pt6.html

Categories