Home > database >  Data gone after refresh page
Data gone after refresh page

Time:11-02

My data is gone after refresh page.

Scenario:

LucrariComponent (Data shown) -> refresh page -> LucrariComponent (No data shown)

The data only shown at the first load, but then it's gone whenever I change the page or refresh the page.

On console log i receive the data from the api in page - but i only get this: enter image description here

Using a template with routes.

HTML


<tr *ngFor="let lucrare of lucrari">
          <td>
            <a href="#" >
              {{ lucrare.projectNumber }}
            </a>
          </td>
          <td>
            <a
              href="#"
              
            >
            {{ lucrare.projectRegion }}
            </a>
            <span 
              >{{ lucrare.addressLine }}</span
            >
          </td>
</tr>

Component.ts

import { Component, OnInit } from '@angular/core';
import { PostService } from '../../services/post.service';

@Component({
  selector: 'app-lista-lucrari',
  templateUrl: './lista-lucrari.component.html',
})
export class ListaLucrariComponent implements OnInit{
  lucrari:any;

  constructor(private service:PostService) {
    
  }

  ngOnInit() {
    this.getLucrari()
  };

  getLucrari(): void {
    this.lucrari = [];
    this.service.getLucrari().subscribe(response => {
      this.lucrari = response;
      console.log(this.lucrari);
    });

  }
}
 

Service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import {AuthService} from "../modules/auth";

@Injectable({
  providedIn: 'root'
})

export class PostService {
  private url = 'api-url';

  constructor(private httpClient: HttpClient, private authService: AuthService) { }

  getLucrari(){
    return this.httpClient.get(this.url, { headers: new HttpHeaders({'Authorization': 'Bearer '   this.authService.currentUserValue})});
  }

}

It's my first angular project - so I may mess up easy things. Thanks for understanding.

I've tried almost all solutions that i could find. Most likely i don't search for the right thing, since i'm new to angular.

CodePudding user response:

Try this:

In your ListaLucrariComponent component, change your constructor to

constructor(private service:PostService, private cdr: ChangeDetectorRef) {}

Then, modify your getLucari method to

getLucrari(): void {
    this.lucrari = [];
    this.service.getLucrari().subscribe(response => {
      this.lucrari = response;
      this.cdr.detectChanges()
      console.log(this.lucrari);
    });

  }

This should cause *ngFor to trigger again, and rerun the logic that renders your page.

  • Related