In Angular 13, I created basic CRUD app of employee. When i insert new data and hit submit it run the createEmployee() service and print data on console. Then it redirect to home page that shows all entry in table which call getEmployeeList(). But sometimes it shows newly created entry and sometimes it not shows. In database it perfectly entered. When i goto some other page and come back to home page it shows.
create-employee.components.ts
import { Component, OnInit } from '#angular/core';
import { Router } from '#angular/router';
import { Employee } from 'src/app/employee';
import { EmployeeService } from 'src/app/Services/employee.service';
#Component({
selector: 'app-create-employee',
templateUrl: './create-employee.component.html',
styleUrls: ['./create-employee.component.css']
})
export class CreateEmployeeComponent implements OnInit {
employee: Employee = new Employee();
constructor(private employservice: EmployeeService,private router: Router) { }
ngOnInit(): void {
}
saveEmployee() {
this.employservice.createEmployee(this.employee).subscribe(data => {
console.log(data);
})
console.error();
}
gotoemployeelist() {
this.router.navigate(['employees']);
}
onSubmit() {
this.saveEmployee();
this.gotoemployeelist();
}
}
employee-service.ts
import { HttpClient } from '#angular/common/http';
import { Injectable } from '#angular/core';
import { map, Observable } from 'rxjs';
import { Employee } from '../employee';
#Injectable({
providedIn: 'root'
})
export class EmployeeService {
public baseURL="http://localhost:8080/api/v1/employees";
constructor(private httpClient: HttpClient) {}
getEmployeeList(): Observable<Employee[]> {
return this.httpClient.get<Employee[]>(this.baseURL).pipe(
map(employees => {
for(let employee of employees) {
employee.bdate = new Date(employee.bdate);
employee.jdate = new Date(employee.jdate);
}
console.log("Employees Service: GetEmployee() called");
return employees;
}));
}
createEmployee(employee: Employee): Observable<Object> {
console.log("Employees Service: CreateEmployee() called");
return this.httpClient.post(this.baseURL,employee);
}
getEmployeebyId(id: Number): Observable<Employee> {
console.log("Employees Service: GetEmployeeById() called");
return this.httpClient.get<Employee>(this.baseURL+"/"+id);
}
updateEmployee(employee: Employee,id: number): Observable<Object> {
console.log("Employees Service: UpdateEmployee() called");
console.log(employee);
return this.httpClient.put(this.baseURL+"/"+id,employee);
}
deleteEmployee(id: number): Observable<Object> {
console.log("Employees Service: DeleteEmployee() called");
return this.httpClient.delete(this.baseURL+"/"+id);
}
}
Home-component.ts
import { Component, OnInit } from '#angular/core';
import { Router } from '#angular/router';
import { Employee } from 'src/app/employee';
import { EmployeeService } from 'src/app/Services/employee.service';
#Component({
selector: 'app-employee-list',
templateUrl: './employee-list.component.html',
styleUrls: ['./employee-list.component.css',]
})
export class EmployeeListComponent implements OnInit {
employees: Employee[];
constructor(private employeeservice: EmployeeService,private router: Router) {
}
ngOnInit(): void {
this.getEmployees();
}
private getEmployees() {
this.employeeservice.getEmployeeList().subscribe(data => {
console.log(data);
this.employees=data;
});
}
updateEmployee(id: Number) {
this.router.navigate(['update-employee',id]);
}
deleteEmployee(id: number) {
this.employeeservice.deleteEmployee(id).subscribe(data => {
console.log(id+"employeed Deleted.");
this.getEmployees();
});
}
employeeDetails(id: number) {
this.router.navigate(['emloyee-details',id]);
}
}
In console you can see that createEmployee() called then GetEmployee() called and then it print console.log(newEntry) after navigation.
What is happening program is not waiting to complete createEmployee API before navigating to the home page. You need to call gotoemployeelist() only after the you get response from createEmployee API. You can do this by calling the method inside the subscribe
saveEmployee() {
this.employservice.createEmployee(this.employee).subscribe(data => {
console.log(data);
this.gotoemployeelist();
})
console.error();
}
gotoemployeelist() {
this.router.navigate(['employees']);
}
onSubmit() {
this.saveEmployee();
}
1.here is my websocket.service.ts file
import { Injectable } from '#angular/core';
import { Observable, } from 'rxjs';
import {io} from 'socket.io-client';
#Injectable({
providedIn: 'root'
})
export class WebsocketService {
socket: any;
readonly uri: string = "ws://localhost:3000";
constructor() {
this.socket = io(this.uri);
}
listen(eventName: string, data:any){
return new Observable((subscriber) => {
this.socket.on(eventName, (data) => {
subscriber.next(data)
})
})
}
emit(eventName: string , data: any){
this.socket.emit(eventName,data);
}
}
here is my app.components.ts file
import { Component, OnInit } from '#angular/core';
import { WebsocketService } from './websocket.service';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'socket-io-example';
constructor( private websockerservice: WebsocketService){
}
ngOnInit(){
// here we want to listen to an event from socket.io server
this.websockerservice.listen('test event','data').subscribe((data) =>{
console.log(data);
})
}
}
here is my node.js, socket-io.server.js file
var server = require('http').Server(app); //here i got refernce error: app is not defined
~~~
var io = require('socket.io')(server);
io.on('connection', function(socket){
console.log("A user cconnected");
socket.emit('test event', 'here is some data');
});
server.listen(3000, () => {
console.log("server.io server is listing to port 3000")
});
You must define app first. With express you can do the following:
const express = require('express');
var app = express();
I'm writing a chat app and I'm using a Node server and socket.io server side and Angular and socket.io-client client side. Unfortunately I get a "this.socketService.getMessage(...).subscribe is not a function" error when I run it. Everything else seems to work.
app.component.ts:
import { Component, OnInit, OnDestroy } from '#angular/core';
import { SocketService } from './socket.service';
import { Observable } from 'rxjs';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'chat';
registered = false;
username: string;
constructor(public socketService: SocketService) {
}
ngOnInit(): void {
this.socketService
.getMessage()
.subscribe(msg => {
if (msg === 'Registered') {
this.registered = true;
console.log(this.registered)
}
});
}
register(username: string): void {
console.log(username)
this.username = username;
this.socketService.sendMessage('register', username);
}
send(message: string): void {
this.socketService.sendMessage('message', message);
}
}
socket.service.ts:
import { Injectable } from '#angular/core';
import { io } from 'socket.io-client';
import { Observable } from 'rxjs';
#Injectable({
providedIn: 'root'
})
export class SocketService {
socket;
constructor() {
this.socket = io('http://localhost:3000/');
}
getMessage(): Observable<any> {
return this.socket.on('message', msg => {
console.log(msg);
});
}
sendMessage(type: string, words: any): void {
console.log(type, words);
this.socket.emit(type, words);
}
}
this.socket.on doesn't returns an Observable so you can't .subscribe() as you would do with an observable.
It returns a Socket as described into the docs : https://socket.io/docs/v3/client-api/#socket-on-eventName-callback
want to call a rest API from a nodeJS server with a click of a button in my project angular to add a user in the database, the api in the server is connected to my mysql database , just i wonna invoke the api rest of add ou update ou delete from the button in my project angular . I am new to this I dont know how to proceed.
thank you
import { Component } from '#angular/core';
import { LocalDataSource } from 'ng2-smart-table';
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { SmartTableData } from '../../../#core/data/smart-table';
//import { EmailValidator } from '#angular/forms';
#Injectable()
export class ConfigService {
constructor(private http: HttpClient) { }
}
#Component({
selector: 'ngx-smart-table',
templateUrl: './smart-table.component.html',
styles: [`
nb-card {
transform: translate3d(0, 0, 0);
}
`],
})
#Injectable()
export class Configuration {
public server = 'http://localhost:3000/';
public apiUrl = 'api/';
public serverWithApiUrl = this.server + this.apiUrl;
}
export class SmartTableComponent {
settings = {
add: {
addButtonContent: '<i class="nb-plus"></i>',
createButtonContent: '<i class="nb-checkmark"></i>',
cancelButtonContent: '<i class="nb-close"></i>',
actionButonContent:'<i (click)="makeServiceCall($event)"><i/>',
},
edit: {
editButtonContent: '<i class="nb-edit"></i>',
saveButtonContent: '<i class="nb-checkmark"></i>',
cancelButtonContent: '<i class="nb-close"></i>',
actionButonContent:'<i (click)="onEditConfirm($event)"></i>'
},
delete: {
deleteButtonContent: '<i class="nb-trash"></i>',
confirmDelete: true,
actionButonContent:'<i (click)="onDeleteConfirm($event)"></i>'
},
columns: {
id: {
title: 'ID',
type: 'number',
},
firstName: {
title: ' Name',
type: 'string',
},
email: {
title: 'E-mail',
type: 'string',
},
password: {
title: 'password',
type: 'password',
},
},
};
source: LocalDataSource = new LocalDataSource();
constructor(private service: SmartTableData) {
const data = this.service.getData();
this.source.load(data);
}
onDeleteConfirm(event): void {
if (window.confirm('Are you sure you want to delete?')) {
event.confirm.resolve();
} else {
event.confirm.reject();
}
}
}
and this is my app.js (server)
var express = require('express');
var router = express.Router();
var user=require('../model/user');
router.get('/:id?',function(req,res,next){
if(req.params.id){
user.getUserById(req.params.id,function(err,rows){
if(err)
{
res.json(err);
}
else{
res.json(rows);
}
});
}
else{
user.getAllUsers(function(err,rows){
if(err)
{
res.json(err);
}
else
{
res.json(rows);
}
});
}
});
router.post('/',function(req,res,next){
user.addUser(req.body,function(err,count){
if(err)
{
res.json(err);
}
else{
res.json(req.body);
}
});
});
router.delete('/:id',function(req,res,next){
user.deleteUser(req.params.id,function(err,count){
if(err)
{
res.json(err);
}
else
{
res.json(count);
}
});
});
router.put('/:id',function(req,res,next){
user.updateUser(req.params.id,req.body,function(err,rows){
if(err)
{
res.json(err);
}
else
{
res.json(rows);
}
});
});
module.exports=router;
To make a call you need to add the HttpClientModule in your app.module.ts as import.
Then inject the Http client it wherever you want to use it:
constructor(private http: HttpClient){}
to use it just do:
this.http.get(<<url>>) //for get request
this.http.post(<<url>>,obj) //for post request
this returns an observable from which you can map the results and catch errors using Rxjs operators. for eg
addUser(user){ //called on button click
this.http.post(yourUrl,Json.Stringify(user)).pipe(
map((res)=>{
//do something with response
return 'sucess'
}),
catchError(err => {
//handleError
}
).subscribe(); // dont forget to subscribe
}
if you want to learn more : https://angular.io/guide/http
and for rxjs: https://www.learnrxjs.io/
Assume that the data that needs to be sent to the server is being passed to the function as the "data" parameter. Add "HttpClientModule" to the main app module or to your custom module if any as follows. Custom service has been imported in the app module or import it in your module accordingly.
app.module.ts
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { FormsModule } from '#angular/forms';
import { HttpClientModule } from '#angular/common/http';
import { CustomService } from 'location-of-custom-service';
#NgModule({
imports: [
CommonModule,
FormsModule,
HttpClientModule
],
declarations: [],
providers: [CustomService]
})
export class AppModule { }
Create a service file as follows.
custom.service.ts
import { Injectable } from '#angular/core';
import { Router } from '#angular/router';
import { HttpClient, HttpHeaders } from '#angular/common/http';
import { Observable, throwError } from 'rxjs';
import { retry, catchError } from 'rxjs/operators';
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
#Injectable({
providedIn: 'root'
})
export class CustomService {
public server = 'http://localhost:3000/';
public apiUrl = 'api/';
public serverWithApiUrl = this.server + this.apiUrl;
private fetchDataURL = this.serverWithApiUrl + 'fetchSomeData';
private addDataURL = this.serverWithApiUrl + 'addSomeData'
constructor(private _http: HttpClient) { }
// Fetch data
fetchData(id): Observable<any> {
this.fetchDataURL = this.fetchDataURL + "/" + id;
return this._http.get<any>(this.fetchDataURL, httpOptions)
.pipe(
retry(1),
catchError(this.handleError)
);
}
// Add data
addData(data): Observable<any> {
return this._http.post<any>(this.addDataURL, data, httpOptions);
}
// Error handler - you can customize this accordingly
handleError(error) {
let errorMessage = '';
if (error.error instanceof ErrorEvent) {
// client-side error
errorMessage = `Error: ${error.error.message}`;
} else {
// server-side error
errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
}
return throwError(errorMessage);
}
}
Your existing component has been modified so as to have the new additions as follows.
smarttable.component.ts
import { Component, OnInit } from '#angular/core';
import { Router, ActivatedRoute } from '#angular/router';
import { FormControl, FormGroup, Validators } from '#angular/forms';
import { CustomService } from './custom-service-location';
#Component({
selector: 'ngx-smart-table',
templateUrl: './smart-table.component.html'
})
export class SmartTableComponent implements OnInit {
constructor(private customService: CustomService) {}
fechedData: any;
// you existing codes goes here
// Add data - assume the data that needs to be sent to the server is as "data"
makeServiceCall(data) {
this.customService.addData(data)
.subscribe((data) => {
console.log(data);
// your logic after data addition goes here
},
(error) => {
// logic to handle error accordingly
});
}
// Fetch data
getData(id) {
this.customService.fetchData(id)
.subscribe((data) => {
console.log(data);
this.fechedData = data;
// your logic after data fetch goes here
},
(error) => {
// logic to handle error accordingly
});
}
}
I hope the above helps.
I am trying to make a socket io client I am able to connect but I am not able to emit or receive message.I have create a web app Where If any user connect it shows new user is connected, so If I open My app It shows new user is connected but when I send message It does not show on the either side
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import * as io from 'socket.io-client';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
socket:any;
socketURL:any;
constructor(public navCtrl: NavController) {
this.socketURL = "my url";
this.socket = io(this.socketURL);
this.socket.on('connect',()=> {
console.log('connected from server');
})
this.socket.emit('createMessage', 'hello worlddddddddd');
this.socket.on('newMessage', (message)=>{
alert('new massage'+JSON.stringify(message));
}
)
}
ionViewWillleave(){
this.socket.on('disconnect',()=> {
console.log('disconnected from server');
});
}
}
I have this in my case and it works.
constructor(privatesocketService: SocketService, privatesocket: Socket){
this.socket.on('message', (data) = > {
console.log('message : ' + data);
});
}
ionViewDidLeave(){
console.log('ionViewDidLeave ChatRoomPage');
this.socketService.leaveConversation(this.conversationId);
}
ionViewDidLoad(){
console.log('ionViewDidLoad ChatRoomPage');
this.socketService.joinConversation(this.conversationId);
this.getUsers();
}
sendMessage(){
this.conversationService.sendMessage(this.conversationId, this.message);
}
import {Injectable} from '#angular/core';
import {Socket} from 'ng-socket-io';
#
Injectable()
export class SocketService {
constructor(privatesocket: Socket) {
this.socket.connect();
}
joinConversation(conversationId) {
this.socket.emit('enter-room', conversationId);
}
leaveConversation(conversationId) {
this.socket.emit('leave-room', conversationId);
}
sendMessage(conversationId) {
this.socket.emit('new-message', conversationId);
}
}