Home > Net >  Angular - Update view on changes
Angular - Update view on changes

Time:07-05

I have a page that displays a list of users, when I add a new user (using a form) the list doesn't immediately displays the new user that i added, but i need to reload the page to see the updated list and I can't figure out why since I stored the list of users in a BehaviourSubject. Maybe it doesn't update because i populate the behaviour subject in the ngOnInit method?! But I would't know where else I could do the call to the API apart from the ngOnInit method.

Here's my code:

export interface User {
  uuid: string;
  name: string;
  surname: string;
  email: string;
  password: string;
}

@Component({
  selector: 'my-app',
  template: `
    <button  (click)="addUser=!addUser">Add</button>
    <ul>
      <li *ngFor="let user of (users$ | async)">{{user.name}}</li>
    </ul>

    <div  *ngIf="addUser">
    <form [formGroup]="userForm" (ngSubmit)="addNewUser()">

     <!-- NAME & SURNAME INPUT -->
     <table  cellspacing="0">
       <tr>
         <td>
           <input matInput formControlName="name" type="text">
        </td>
        <td>
           <input matInput formControlName="surname" type="text">
        </td>
    </tr>
</table>

<table  cellspacing="0">
  <tr>
    <td>
      <input matInput formControlName="email" type="text">
    </td>
    <td>
      <input matInput formControlName="password" type="text">
    </td>
  </tr>
</table>


<button  type="submit">Add User</button>
<button  (click)="addUser=!addUser">Cancel
</button>
</form>
 </div>
`})
 export class AppComponent {
     users$ = new BehaviorSubject<User[]>([]);
     addUser: boolean = false;

     userForm = this.fb.group({
        name: ['', [Validators.required]],
        surname: ['', [Validators.required]],
        email: ['', [Validators.required]],
        password: ['', [Validators.required]],
     });

     constructor(
        private http: HttpClient,
        private fb: FormBuilder,
        private router: Router
     ) {}

     ngOnInit(): void {
       this.http.get<User[]>('http://localhost:3000/users').subscribe((res) => this.users$.next(res));
      }

      get name() {
        return this.userForm.get('name')!;
      }

      get surname() {
         return this.userForm.get('surname')!;
       }

      get email() {
        return this.userForm.get('email')!;
      }

      get password() {
          return this.userForm.get('password')!;
      }

       addNewUser() {
           if (this.userForm.valid) {
              this.http.post<Omit<User, 'id'>>('http://localhost:3000/users', this.userForm.value).subscribe(
              (next) => console.log('N: ', next),
              (err) => console.log('E: ', err)
             );
          }
        }
        }

CodePudding user response:

@juniorDev

Since you are adding, you need to modify the array as you add

addNewUser() {
           if (this.userForm.valid) {
              this.http.post<Omit<User, 'id'>>('http://localhost:3000/users', this.userForm.value).subscribe(
              (next) => {
                console.log('N: ', next);
                const newUsersValue = (this.users$.value || []).concat(this.userForm.value);
                this.users$.next(newUsersValue);
              },
              (err) => console.log('E: ', err)
             ),
          }
        }
     }

CodePudding user response:

recall your ueser get api method after calling your user add api method.

   this.http.get<User[]>('http://localhost:3000/users').subscribe((res) => this.users$.next(res));

It will show your list with new adding user.

  • Related