首先需要确认数据是否被正确地传递到了组件内。如果数据已经成功地传递进来了,但仍然无法在页面中显示出来,那么就需要检查数据绑定是否正确。在模板中,确保绑定的是正确的属性,如下所示:
{{ data.property }}
如果还是无法显示数据,那么就需要考虑在页面刷新后重新请求数据。可以使用 Angular 的路由守卫来在每次导航到组件时重新获取数据:
@Injectable()
export class GetDataGuard implements CanActivate {
constructor(private dataService: DataService) { }
canActivate(): Observable {
return this.dataService.getData().pipe(
tap((data) => {
// 将数据存储在服务中,以便在组件中使用
this.dataService.setData(data);
}),
map(() => true),
catchError(() => of(false))
);
}
}
然后在组件的路由中,将该守卫添加到 canActivate 数组中:
const routes: Routes = [
{
path: 'data',
component: DataComponent,
canActivate: [GetDataGuard]
}
];
最后,在组件中,可以使用订阅来获取来自服务的数据:
export class DataComponent implements OnInit {
data: any;
constructor(private dataService: DataService) { }
ngOnInit(): void {
this.dataService.getData().subscribe((data) => {
this.data = data;
});
}
}