signalR hub 2 connection fails using angular 5 and MVC5 - asp.net-mvc-5

i tried to make use of this post:
https://codingblast.com/asp-net-core-signalr-chat-angular/
and make connection to signalR hub using angular 5. but when i run the project i see this message in console:
Error: Failed to start the connection. SyntaxError: Unexpected end of JSON input
app.component.ts:24 Error while establishing connection :(
here is my component:
import { Component, OnInit } from '#angular/core';
import { HubConnection } from '#aspnet/signalr-client';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'app';
private _hubConnection: HubConnection;
nick = '';
message = '';
messages: string[] = [];
public getRealTime(): void {
this._hubConnection
.invoke('getRealTime')
.catch(err => console.error(err));
}
ngOnInit() {
this._hubConnection = new HubConnection('/clockHub');
this._hubConnection
.start()
.then(() => console.log('Connection started!'))
.catch(err => console.log('Error while establishing connection :('));
this._hubConnection.on('setRealTime', (time: string) => {
alert(time);
});
}
}
and also code for hub class is:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
namespace clockHub
{
public class ClockHub : Hub
{
public void GetRealTime()
{
Clients.Caller.setRealTime(DateTime.Now.ToString("h:mm:ss tt"));
}
}
}
Thank You.

Related

connect to Binance websocket api from Nestjs

I wanna connect to the binance websocket api but I don't know how
I tried connecting to a specific url by making nestjs server a client but it doesn't console.log 'connected to the binance'
import { Injectable, OnModuleInit } from '#nestjs/common';
import { io, Socket } from 'socket.io-client'
#Injectable()
export class BinanceGateway implements OnModuleInit {
public binanceClient: Socket
constructor() {
this.binanceClient = io('https://api.binance.com')
}
onModuleInit() {
console.log('hello')
this.registerConsumerEvents()
}
registerConsumerEvents() {
this.binanceClient.on('connect', () => {
console.log('connected to the binance')
})
}
}
I find the solution to my question.
In order to access the binance websocket api with Nest.js, first, import binance-api-node :
const Binance = require('binance-api-node').default;
Then initialize it in the constructor of BinanceGateway class :
constructor() {
this.binanceClient = Binance()
}
Now you can get data from binanceClient; In my case I wanna get Candle Data So to get Candle Data :
this.binanceClient.ws.candles('ETHBTC', '1m', candle => {
console.log(candle)
})
Now, The final version of binance.gateway.ts is :
import { Injectable, OnModuleInit } from '#nestjs/common';
const Binance = require('binance-api-node').default;
#Injectable()
export class BinanceGateway implements OnModuleInit {
public binanceClient: any
constructor() {
this.binanceClient = Binance()
}
onModuleInit() {
console.log('hooooy')
this.binanceClient.ws.candles('ETHBTC', '1m', candle => {
console.log(candle)
})
}
}

SocketIO events are not triggered when webapp is opened in mobile device

I am working on a simple app where events are triggered once user logs in successfully.
All the events are working fine in my laptop but when i login from my phone, no events are getting triggered? Any possible reason?
Added Angular socket service code below:
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import * as io from 'socket.io-client';
import { Observable } from 'rxjs';
#Injectable({
providedIn: 'root'
})
export class SocketService {
public prod = 'https://afad.sdfsd.com';
public dev = 'http://localhost:3001';
public baseUrl = this.dev;
private socket;
constructor(public http: HttpClient) {
this.socket=io('https://dfdsfs.sdfs.com')
}
public verifyUser=()=>{
return Observable.create((observer)=>{
this.socket.on('verifyUser',(data)=>{
observer.next(data);
})
})
}
public setUser=(authToken)=>{
this.socket.emit("set-user",authToken)
}
public userOffline=()=>{
return Observable.create((observer)=>{
this.socket.on('userOffline',(data)=>{
observer.next(data);
})
})
}
public userList=()=>{
return Observable.create((observer)=>{
this.socket.on('userlist',(data)=>{
observer.next(data);
})
})
}
public welcomeUser=(userid)=>{
return Observable.create((observer)=>{
this.socket.on(userid,(data)=>{
observer.next(data);
})
})
}
public userOnline=()=>{
return Observable.create((observer)=>{
this.socket.on('userOnline',(data)=>{
observer.next(data);
})
})
}
public disconnectUser = () => {
return Observable.create((observer) => {
this.socket.on('disconnect', () => {
observer.next()
})
})
}
}
I have installed socketio-client to achieve this functionality.
Any breakthrough will be helpful
I guess your laptop and phone are connected via WIFI to the router. If so you won't be able to use https://afad.sdfsd.com or http://localhost:3001 due to them only being available only on the laptop.
Try pulling the hostname from the browser and use it as the base URL (window.location.host)
when you are using the laptop it will be localhost:3001 and for the phone it will be IP_OF_THE_3001.
...
export class SocketService {
private socket;
constructor(public http: HttpClient) {
this.socket=io(window.location.host)
}
...
}
I was able to figure out the issue here,
socket.emit will emit an event to only current user, We should use myio.emit in this case.

Angular 7 / Material DataTable not updating after any operation

I'm building an Angular 7 application using #angular/material. When I load the application for the first time, the Datatable renders correctly, but when I call any function, example - delUser, after deleting a user from the database, it's meant to render the table immediately, but it doesn't until I refresh the whole page. I've tried everything, but to no avail.
Here's my code:
import { Component, OnInit, ViewChild, TemplateRef } from '#angular/core';
import { UserService } from 'src/app/services/user.service';
import { MatTableDataSource } from '#angular/material/table';
import { MatSort } from '#angular/material/sort';
import { MatPaginator } from '#angular/material/paginator';
#Component({
selector: 'app-users',
templateUrl: './users.component.html',
styleUrls: ['./users.component.css']
})
export class UsersComponent implements OnInit {
pgtitle:string = "Manage Users";
dataSource:any;
displayedColumns:string[] = ['userName','email','roleId','userType','Actions'];
#ViewChild(MatSort, {static: true}) sort: MatSort;
#ViewChild(MatPaginator) paginator: MatPaginator;
constructor(
private service:UserService
){}
ngOnInit(): void {
this.getAllUsers();
}
applyFilter(filterValue:String){
this.dataSource.filter = filterValue.trim().toLowerCase();
}
getAllUsers(){
this.service.getAllUsers().subscribe( result => {
this.dataSource = new MatTableDataSource(result);
this.dataSource.paginator = this.paginator;
this.dataSource.sort = this.sort;
});
}
delUser(id){
this.service.deleteUser(id).subscribe(result => {
this.getAllUsers();
});
}
Maybe you can try this:
this.service.getAllUsers().subscribe( result => {
this.dataSource = null; //add this
this.dataSource = new MatTableDataSource(result);
this.dataSource.paginator = this.paginator;
this.dataSource.sort = this.sort;
});

Ionic 4 - Camera - Runtime Error - Object(...) is not a function

I'm creating an Ionic app with camera function. I used for this the doc from ionic-framework Ionic native camera
But I get an error when I tried to display the app on my Android device and click onto the "Take a Picture" button.
Error
"Runtime Error Object(…) is not a function"
"TypeError: Object(…) is not a function at Camera.getPicture"
home.ts
import { Component } from '#angular/core';
import { NavController, PopoverController, ViewController } from 'ionic-angular';
import { UserServiceProvider } from './../../providers/user-service/user-service';
import { Camera, CameraOptions, DestinationType, EncodingType, MediaType } from '#ionic-native/camera/ngx';
#Component({
selector: 'page-home',
templateUrl: 'home.html',
})
export class HomePage {
constructor(public navCtrl: NavController, public popoverCtrl: PopoverController, private camera:Camera) {}
myPhoto:any=''
takePicture(){
const options: CameraOptions = {
quality:100,
destinationType: this.camera.DestinationType.FILE_URI,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE
}
this.camera.getPicture(options).then((imageData)=>{
this.myPhoto=(<any>window).Ionic.WebView.convertFileSrc(imageData);
}, (err) => {
// Error log
});
}
openMoreSetting(event) {
let popover = this.popoverCtrl.create(PopoverPage);
popover.present({
ev: event
});
}
}
#Component({
template: `
<ion-list>
<button ion-item>Menu für Settings</button>
</ion-list>
`
})
export class PopoverPage {
constructor(private userServiceProvider: UserServiceProvider,
private viewCtrl: ViewController) {
}
close() {
this.viewCtrl.dismiss();
}
}

getting query params from url Angular

I want to grab id from url http://localhost:4200/courses/5a0eb3d7f6b50c2589c34e57 so in my app.module.ts I have such route {path:'courses/:id', component:CourseComponent, canActivate:[AuthGuard]} and in my course.component.ts I have the following code :
import { Component, OnInit } from '#angular/core';
import { ActivatedRoute } from '#angular/router';
#Component({
selector: 'app-course',
templateUrl: './course.component.html',
styleUrls: ['./course.component.css']
})
export class CourseComponent implements OnInit {
id: String;
constructor(private route: ActivatedRoute) { }
ngOnInit() {
this.id = this.route.snapshot.queryParams["id"];
console.log(this.id)
}
}
Actually in my developer console I can see following
And if I try to console.log(params) I get following
You should use rxjs.
this.route.params.pluck('id').subscribe(v => console.log(v));
Preferable, since .params might be depracated soon:
this.route.paramMap.subscribe(paramMap => paramMap.get('id'));
Everything is in documentation... https://angular.io/guide/router#parammap-api
This is a route param and you should be using the params property
this.id = this.route.snapshot.params["id"];

Resources