我的数据在刷新页面后消失了。
设想情况:
LucrariComponent (数据显示) ->刷新页面-> LucrariComponent (未显示数据)
数据只在第一次加载时显示,但每当我更改页面或刷新页面时,数据就会消失。
在控制台日志中,我从页面中的api接收数据--但我只得到以下内容:

使用带有路由的模板。
HTML
<tr *ngFor="let lucrare of lucrari">
<td>
<a href="#" class="text-dark fw-bolder text-hover-primary fs-6">
{{ lucrare.projectNumber }}
</a>
</td>
<td>
<a
href="#"
class="text-dark fw-bolder text-hover-primary d-block mb-1 fs-6 region"
>
{{ lucrare.projectRegion }}
</a>
<span class="text-muted fw-bold text-muted d-block fs-7"
>{{ 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})});
}
}这是我的第一个角度项目,所以我可能会搞砸容易的事情。感谢您的理解。
我已经尝试了几乎所有我能找到的解决方案。很可能我不去寻找正确的东西,因为我是刚接触过棱角的。
发布于 2022-11-02 09:42:16
试试这个:
在ListaLucrariComponent组件中,将构造函数更改为
constructor(private service:PostService, private cdr: ChangeDetectorRef) {}
然后,将getLucari方法修改为
getLucrari(): void {
this.lucrari = [];
this.service.getLucrari().subscribe(response => {
this.lucrari = response;
this.cdr.detectChanges()
console.log(this.lucrari);
});
}这将导致*ngFor再次触发,并重新运行呈现页面的逻辑。
https://stackoverflow.com/questions/74285552
复制相似问题