0
I wanted to know how I do so that every time I update the data in the database it updates the Component on the angular or refresh page, or better that the service is in real time.
I’ve seen several questions, I even found some, but it was to update the component with the user adding data.
What I want to know is: how to make the database do an update and everyone who is logged in has their components updated with the new information.
This is my code, I have to change something in it? or change something in app.module.ts? Or I don’t know, I don’t know how to get started...
ASP.NET Core 2.2 I’m using Pomelo Framework 2.2 as well Mysql
import { Component, OnInit, ViewChild } from '@angular/core';
import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
import { Madeira } from '../../../../model/madeiras/madeira';
import { MadeiraService } from '../../../../services/madeiras/madeira.service';
import { MatPaginator } from '@angular/material';
import { Router } from '@angular/router';
import { Subscription, interval } from 'rxjs';
@Component({
selector: 'pesquisa-madeira',
templateUrl: './pesquisa.madeira.component.html',
styleUrls: ['./pesquisa.madeira.component.css']
})
export class PesquisaMadeiraComponent implements OnInit {
//private updateSubscription: Subscription;
public madeiras: Madeira[];
@ViewChild(MatSort, { static: true }) sort: MatSort;
@ViewChild(MatPaginator, { static: true }) paginator: MatPaginator;
displayedColumns: string[] = ['id', 'descricao', 'espessura', 'largura', 'comprimento', 'preBenef', 'tipo', 'especie', 'controle', 'imagem', 'editar', 'deletar'];
dataSource = new MatTableDataSource<Madeira>();
ngOnInit() {
//this.updateSubscription = interval(1000).subscribe(
// (val) => {
// this.updateStats()
// });
this.obterTodosMadeira();
this.dataSource.paginator = this.paginator;
this.dataSource.sort = this.sort;
sessionStorage.removeItem('madeiraSession');
}
constructor(private madeiraService: MadeiraService, private router: Router) {
//this.madeiraService.obterTodosMadeira()
// .subscribe(
// madeiras => {
// this.madeiras = madeiras;
// },
// e =>{
// console.log(e.error);
// });
}
public obterTodosMadeira() {
this.madeiraService.obterTodosMadeira()
.subscribe(
madeiras => {
this.madeiras = madeiras;
this.dataSource.data = madeiras;
//this.ngOnInit();
},
e => {
console.log(e.error);
});
}
public adicionarMadeira() {
this.router.navigate(['/madeira']);
}
public editar(madeira: Madeira) {
sessionStorage.setItem('madeiraSession', JSON.stringify(madeira));
this.router.navigate(['/madeira']);
}
public deletar(madeira: Madeira){
var retorno = confirm("Deseja realmente deletar esse item?");
if (retorno == true) {
this.madeiraService.deletar(madeira).subscribe(
madeiras => {
this.madeiras = madeiras;
this.dataSource.data = madeiras;
},
e => {
console.log(e.errors);
}
)
}
}
//FILTRO DE TABELA
applyFilter(filterValue: string) {
this.dataSource.filter = filterValue.trim().toLowerCase();
if (this.dataSource.paginator) {
this.dataSource.paginator.firstPage();
}
}
}
Madeira.Service:
import { Injectable, Inject, OnInit } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Madeira } from '../../model/madeiras/madeira';
@Injectable({
providedIn: 'root'
})
export class MadeiraService implements OnInit {
private baseUrl;
public madeiras: Madeira[];
constructor(private http: HttpClient, @Inject('BASE_URL') baseUrl: string) {
this.baseUrl = baseUrl;
}
ngOnInit(): void {
this.madeiras = [];
}
get headers(): HttpHeaders {
return new HttpHeaders().set('content-type', 'application/json');
}
public cadastrar(madeira: Madeira): Observable<Madeira> {
return this.http.post<Madeira>(this.baseUrl + 'api/madeira', JSON.stringify(madeira), { headers: this.headers });
}
public salvar(madeira: Madeira): Observable<Madeira> {
return this.http.post<Madeira>(this.baseUrl + 'api/madeira/salvar', JSON.stringify(madeira), { headers: this.headers });
}
public deletar(madeira: Madeira): Observable<Madeira[]> {
return this.http.post<Madeira[]>(this.baseUrl + 'api/madeira/deletar', JSON.stringify(madeira), { headers: this.headers });
}
public obterTodosMadeira(): Observable<Madeira[]> {
return this.http.get<Madeira[]>(this.baseUrl + 'api/madeira');
}
public obterMadeira(produtoId: number): Observable<Madeira> {
return this.http.get<Madeira>(this.baseUrl + 'api/madeira/obter');
}
public enviarArquivo(arquivoSelecionado: File): Observable<string> {
const formData: FormData = new FormData();
formData.append('arquivoEnviado', arquivoSelecionado, arquivoSelecionado.name);
return this.http.post<string>(this.baseUrl + 'api/madeira/enviarArquivo', formData);
}
}
Controller:
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using SysWas.Domain.Contratos.IMadeiras;
using SysWas.Domain.Entidades.Madeiras;
namespace SysWas.Web.Controllers.Madeiras
{
[Route("api/[Controller]")]
public class MadeiraController : Controller
{
private readonly IMadeiraRepository _madeiraRepository;
private IHttpContextAccessor _httpContextAccessor;
private IHostingEnvironment _hostingEnvironment;
public MadeiraController(IMadeiraRepository madeiraRepository,
IHttpContextAccessor httpContextAccessor,
IHostingEnvironment hostingEnvironment)
{
_madeiraRepository = madeiraRepository;
_httpContextAccessor = httpContextAccessor;
_hostingEnvironment = hostingEnvironment;
}
[HttpGet]
public IActionResult Get()
{
try
{
return Json(_madeiraRepository.ObterTodos());
}
catch (Exception ex)
{
return BadRequest(ex.ToString());
}
}
[HttpPost]
public IActionResult Post([FromBody]Madeira madeira)
{
try
{
madeira.Validate();
if (!madeira.isValidate) {
return BadRequest(madeira.GetMessageValidation());
}
if(madeira.Id > 0)
{
_madeiraRepository.Atualizar(madeira);
}
else
{
madeira.Tipo = null;
madeira.Especie = null;
madeira.Controle = null;
_madeiraRepository.Adicionar(madeira);
}
return Created("api/madeira", madeira);
}
catch (Exception ex)
{
return BadRequest(ex.ToString());
}
}
[HttpPost("Deletar")]
public IActionResult Deletar([FromBody]Madeira madeira)
{
try
{
_madeiraRepository.Remover(madeira);
return Json(_madeiraRepository.ObterTodos());
}
catch (Exception ex)
{
return BadRequest(ex.ToString());
}
}
[HttpPost("enviarArquivo")]
public IActionResult EnviarArquivo()
{
try
{
var formFile = _httpContextAccessor.HttpContext.Request.Form.Files["arquivoEnviado"];
var nomeArquivo = formFile.FileName;
string novoNomeArquivo = GerarNovoNomeArquivo(nomeArquivo);
var pastaArquivos = _hostingEnvironment.WebRootPath + "\\notafiscal\\";
//nome final com a extensao
var nomeCompleto = pastaArquivos + novoNomeArquivo;
using (var streamArquivo = new FileStream(nomeCompleto, FileMode.Create))
{
formFile.CopyTo(streamArquivo);
}
return Json(novoNomeArquivo);
}
catch (Exception ex)
{
return BadRequest(ex.ToString());
}
}
private static string GerarNovoNomeArquivo(string nomeArquivo)
{
var extensao = nomeArquivo.Split(".").Last();
//var arrayNomeCompacto = Path.GetFileNameWithoutExtension(nomeArquivo).Take(10).ToArray();
//var novoNomeArquivo = new string(arrayNomeCompacto).Replace(" ", "-");
var novoNomeArquivo = $"{DateTime.Now.Year}{DateTime.Now.Month}{DateTime.Now.Day}_{DateTime.Now.Hour}{DateTime.Now.Minute}{DateTime.Now.Second}{DateTime.Now.Millisecond}.{extensao}";
return novoNomeArquivo;
}
}
}
Welcome to Sopt! To answer your question you need to add more information. Where is the backend? Which database is used?
– tvdias
Sorry my lack of information, I use mysql, I will edit the question and put the Controller, is there anything else you want to help? Really lost here...
– Luiz C. de Souza Javorski Jr
From the TAG you can see that you use . net core... Also enter the version, because you can influence the response.
– tvdias
I think the question is now better formulated...
– Luiz C. de Souza Javorski Jr
In this case, you could use the signaling. In case they take too long to answer, I’d say take a look in this tutorial.
– tvdias
I will test here, then I already answer you whether you gave or not, I will have to change the whole structure of the project ? with the example above, I have 3 Repository, Domain and Web projects. I will have to change some things not ?
– Luiz C. de Souza Javorski Jr
recommend using websockets
– Eduardo Vargas
Sorry buddy, I never used websocket, how would I do? Could give me a north?
– Luiz C. de Souza Javorski Jr