Error posting after an update with Supabase and Angular

The Problem

I’ve been trying to learn Angular and Supabase for the past few months, and right now I’m trying to build a good ol’ Todo app with CRUD functionalities using Angular and Supabase.

I’ve managed to get it working for the most part, like, everything works until I edit a Todo.

After I submit the updated todo, which works fine, I can’t add new Todos, and I think I know why but I just can’t figure out a way, or the best should I say, to do that. I can still edit other todos, just can’t submit new ones.

What can I do to prevent that from happening?

How can I streamline the current code that I have? Aside from making the Interface in a different file, that was just laziness

The code

component.html:

<form (formGroup)="todoForm">
  <input type="text" formControlName="todo" />
  <button type="submit" (click)="addTodo()" (disabled)="todoForm.invalid">Save</button>
</form>
<mat-divider style="margin: 20px 0;"></mat-divider>
<ul>
  <li *ngFor="let todo of todos | async">
    <span>{{ todo.id }} - {{ todo.todo }}</span>
    <span style="margin-left: 10px">
      <button (click)="deleteTodo(todo)">Delete</button>
    </span>
    <span style="margin-left: 10px">
      <button (click)="updateTodo(todo)">Update</button>
    </span>
  </li>
</ul>

component.ts:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { RealtimeService } from './realtime.service';

export interface Todo {
  id: number;
  todo: string;
}

@Component({
  selector: 'app-realtime-test',
  templateUrl: './realtime-test.component.html',
  styleUrls: ('./realtime-test.component.scss'),
})
export class RealtimeTestComponent implements OnInit {
  todos = this._realtimeServie.todos;

  todoForm!: FormGroup;
  selectedTodo!: Todo;

  constructor(
    private _realtimeServie: RealtimeService,
    private fb: FormBuilder
  ) {}

  ngOnInit(): void {
    this.todoForm = this.fb.group({
      todo: ( '', (Validators.required) ),
    });
  }

  addTodo() {

    if(this.selectedTodo) {
      this._realtimeServie.updateTodo(this.selectedTodo.id , this.todoForm.value)
    } else {
      this._realtimeServie.insertTodo(this.todoForm.value);
    }

    this.resetForm();
  }

  deleteTodo(todo: Todo) {
    this._realtimeServie.deleteTodo(todo.id);
  }

  updateTodo(todo: Todo) {
    this.selectedTodo = todo;

    this.todoForm = this.fb.group({
      todo: ( this.selectedTodo.todo, (Validators.required) )
    })
  }

  resetForm(): void {
    this.todoForm.reset();
  }
}

service.ts:

import { Injectable } from '@angular/core';
import { createClient, SupabaseClient } from '@supabase/supabase-js';
import { BehaviorSubject, Observable } from 'rxjs';

import { environment as env } from 'src/environments/environment';

export interface Todo {
  id: number;
  todo: string;
}

@Injectable({
  providedIn: 'root',
})
export class RealtimeService {
  supabase: SupabaseClient = createClient(
    env.supabaseConfig.supabaseUrl,
    env.supabaseConfig.supabaseKey
  );

  private _todos: BehaviorSubject<any> = new BehaviorSubject(());

  constructor() {
    this.fetchTodos();
    this.handleTodosChanged();
  }

  // This is what the component should call to get the list of todos, instead of getting through the
  // behavior subject instantiated above

  get todos(): Observable<Todo()> {
    return this._todos.asObservable();
  }

  // Fetch all todos from the Todos table
  async fetchTodos() {
    let { data: todos, error } = await this.supabase
      .from<Todo>('todos')
      .select('*');

    console.log('query: ', todos);
    this._todos.next(todos);

    return { todos, error };
  }

  // Insert new todo in the todos table
  async insertTodo(todoForm: Todo) {
    let { data: todo, error } = await this.supabase
      .from<Todo>('todos')
      .insert(todoForm);
    return { todo, error };
  }

  // Remove todo from the todos table
  async deleteTodo(id: number) {
    let { data: todo, error } = await this.supabase
      .from<Todo>('todos')
      .delete()
      .match({ id });
    return { todo, error };
  }

  // Update todo from the todos table
  async updateTodo(id: number, todoForm: Todo) {
    let { data: todo, error } = await this.supabase
      .from('todos')
      .update( todoForm )
      .match({ id });
    return { todo, error };
  }

  // Handle todos change when a change happens in the database
  handleTodosChanged() {
    const mySubscription = this.supabase
      .from('todos')
      .on('*', (payload) => {
        //console log the paylod
        console.log('payload: ', payload);

        // if the payload type is equals to...
        if (payload.eventType == 'INSERT') {
          const newItem: Todo = payload.new;
          this._todos.next((...this._todos.value, newItem));
        } else if (payload.eventType == 'DELETE') {
          const oldTodo: Todo = payload.old;
          const newTodos = this._todos.value.filter(
            (item: { id: number }) => oldTodo.id != item.id
          );
          this._todos.next(newTodos);
        } else if (payload.eventType == 'UPDATE') {
          const updatedTodo: Todo = payload.new;
          const newTodos = this._todos.value.map((item: Todo) => {
            if (updatedTodo.id == item.id) {
              item = updatedTodo;
            }
            return item;
          });
          this._todos.next(newTodos);
        }
      })
      .subscribe();
    return mySubscription;
  }
}

```

angular reactive form custom validator returning value from the API

I have a API the validate claim and returns an object of valid which is true or false and messageLst

I need the custom validate is used display the messageLst by looping throught the values

Angular componente anidado genera un espacio innecesario

Soy nuevo usando angular y no sé como formular mi pregunta espero me puedan ayudar a comprender como funciona este framework.

Tengo creado este componente llamado app-list-item el cual contiene otros componentes hijos:

<app-list-item>
    <app-list-avatar><i class="mdi mdi-send"></i></app-list-avatar>
        <app-list-content>
            <app-list-title>Talara</app-list-title>
            <app-list-subtitle>Ciudad</app-list-subtitle>
         </app-list-content>
  </app-list-item>

El problema está en que genera un ‘espacio’ en cada componente creado
introducir la descripción de la imagen aquí

y así con cada componente.
Espero me ayuden o tenga que reformular la pregunta.

javascript – How to check whether the user completed his missions? (Web Development Angular & nodejs)

I am working on a coding/gaming application, (a one just like coding game).
I am currently stuck in the daily missions part.

So, the user receivers everyday some missions, (eg; solving a problem, following another user, completing a quizz, …) that he has to complete.

The problem is the I didn’t know how to listen for mission Completion?
How will I know whether the user completed his missions or not?
What’s the best approach to implementing such a task?

Here’s a solution I thought of, however, I highly doubt that it is good:

Everytime the user completes a certain task I check whether he had that task as a daily mission, if positive, I’ll mark that mission as complete.
Eg;

onProblemSolve(){
   const missions = this.currentUser.getMissions();
   if(missions.contains('problemSolving')) {
       this.markMissionAsComplete();
   }
}

If you have any articles or tutorials that could clarify this, that would be a huge help

Thank you very much

angular – Ngx datatable bootstrap theme no funciona correctamente con el scrollbar activo

El sombreado de la celda no se muestra a partir de cierta columna cuando tengo el scrollbar-x activo, alguna idea de que puede ser? la clase o quizás el width de la tabla ? gracias

  *ngIf="dataSource"
  #table
  class="bootstrap table"
  style="height: 65vh;"
  (columns)="dataSource.columns"
  (columnMode)="ColumnMode.force"
  (rowHeight)="50"
  (footerHeight)="70"
  (headerHeight)="50"
  (sortType)="SortType.single"
  (rows)="rows"
  (scrollbarV)="true"
  (scrollbarH)="true"
  (virtualization)="false"
  (externalPaging)="true"
  (count)="page.totalElements"
  (offset)="page.pageNumber"
  (limit)="page.size"
  (page)="setPage($event)"
  (sort)="onSort($event)"

Adjunto una imagen del problema

issue

angular – As colunas dos dias da semana no componente Calendar no PrimeNG não renderizam corretamente

Olá, peguei um projeto em que é usado o componente Calendar do PrimeNG mas as colunas do componente estão “comprimidas” e os valores com dois dígitos estão sendo renderizados um sobre o outro, ao invés de um do lado do outro. Gostaria de saber qual propriedade poderia estar configurada para causar isso, como podem ver na imagem em anexo calendar primeng.

Já tentei alterar algumas mas nenhuma reflete no problema.

javascript – Preciso pecorrer um json ultilizando HttpClient em angular, mais não consigo acessar o subnivel do Json

import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';

const url = 'http://localhost:3000';

interface Paises {
  id: number;
  country: string;
  cities: City();
}

interface Cities {
  city: City();
}

interface City {
  id: number;
  city: string;
  lat: number;
  lon: number;
}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ('./app.component.css'),
})
export class AppComponent implements OnInit {
  paises: Paises() = ();
  city: Cities() = ();

  constructor(private httpClient: HttpClient) {}

  ngOnInit(): void {
    this.httpClient.get<Paises()>(`${url}/countries`).subscribe((dados) => {
      this.paises = dados;
      console.log(this.paises);
    });
    console.log(this.paises);
  }
}
<h3>País de origem:</h3>
<select>
  <option *ngFor="let item of paises" value="{{ item.country }}">
    {{ item.country }}
  </option>
</select>

<h3>Cidade de origem:</h3>
<select>
  <div *ngFor="let item of paises">
    <option *ngFor="let item of item.cities" value="{{item.city}}">
    {{item.city}}
    </option>
  </div>
</select>

<h3>Pais de Destino:</h3>
<select>
  <option *ngFor="let item of paises" value="{{ item.country }}">
    {{ item.country }}
  </option>
</select>

<h3>Cidade de Destino:</h3>
<select>
  <option *ngFor="let item of paises" value="{{ item.country }}">
    {{ item.country }}
  </option>
</select>

angular.js – Multiple angular apps at same domain

I was wondering if host multiple angular apps at same domain it can opens some security breach, and if yes, what it will be the best approach to do that in my following scenario:

The project that i’m creating, has the following structure:

  • An API created in Django
  • An APP to final user created in Angular
  • An administrative panel APP created in Angular

And i’m hosting with NGINX with the following rules:

server {
   server_name xxx.xxx.xxx.xx;
   listen 443 ssl;
   
   # Handles proxying to Angular App
   location / {
       alias /home/web/dist/;
       try_files $uri $uri/ /index.html;
   }
   
   # Handles proxying to Angular App - Admin System
   location /panel {
       alias /home/web-admin-panel/dist/;
       try_files $uri $uri/ /panel/index.html;
   }
   
   # Handles proxying to Django API
   location /api {
       include proxy_params;
       proxy_pass http://unix:/home/backend/project.sock;
   }
}

I build the admin app application using ng build --c production --base-href /panel/ to work properly.

angular – Devo Adicionar a pasta node_modules no git?

blz?
Gente, estou criando um projeto em Angular que faz parte de um processo seletivo, e quando fui adicionar o projeto ao git para fazer o commit, o terminal informou que o .gitignore está ignorando a pasta node_modules. Percebi que a pasta tem muitos arquivos, mas é importante e necessário adicioná-la ao git para que o projeto rode do mesmo jeito em outra máquina ou o gestor vai executar isso ao baixar o projeto em sua máquina?

Convertir a pdf en angular

Resulta que estoy trabajando en una api nest donde devuelve un documento pdf a modo de texto. ¿Existe una librería para traer ese archivo como PDF?
Para que me entiendan: esta es la respuesta de la API:

View post on imgur.com

Esta es la forma como estoy trayendo el documento:

    return this.http.get(this.urlSeeDocument+id+'.pdf');
  }