首页 文章

在从Observable订阅数据之前,组件显示空白屏幕

提问于
浏览
1

我目前面临通过Observables订阅数据的问题 . 直到时间数据被订阅并存储在局部变量(对象阵列)中进行显示,同时组件加载,从而不显示数据,因为它仍然从后端获取数据 . 我假设问题是竞争条件(异步),任何关于如何处理这个问题的线索?

我正在读取Json数据,该数据获取'ObjectArray'中的值,并在角度2组件上填充与PrimeNG数据表相同的数据 .

<p-dataTable [value]="ObjectArray">
    <p-column field="label"></p-column>
 </p-dataTable>

订阅代码:

constructor(private store: Store<fromRoot.State>){
    this.metaData$ = store.select(fromRoot.getMetadata);
  }

  this.metaData$.subscribe(
  data => {
    if (data.length > 0) {
      data.forEach(v => this.ObjectArray.push({...v}));
    }
  });

2 回答

  • 0

    您有三个选项使用

    使用 ngIf 或使用新的 ngIf else 和最后一个而不是最少 Router Resolve

    假设您要显示的数据是

    dataAsync:any;

    Using NgIf

    <div *ngIf = "dataAsync">
      {{dataAsync}}
    </div>
    

    Using new If else to show a Loading Prompt

    <ng-template #fetching>
        <p>Fetching...</p>
      </ng-template>
    
      <div *ngIf=" dataAsync; else fetching;">
        <strong>Angular 4 If else Usage - {{dataAsync}}</strong>
      </div>
    

    Router Resolve

    看看这个解决方案的Resolve https://plnkr.co/edit/u2qR9J?p=preview

    @Injectable()
    export class Resolve implements Resolve<any> {
    
      constructor(private service: yourService) {}
    
      resolve(route: ActivatedRouteSnapshot) {
        return this.service.getdata();
      }
    }
    

    在路线

    { 
        path: 'yourpath',
        component: your Component,
        resolve: {
          resolve: Resolve
        }
    

    在组件中使用ngOnInit

    ngOnInit() {
        this.resolve= this.route.snapshot.data['resolve'];
      }
    

    然后在模板中显示解析 .

    请查看我的所有此类Angular概念页面

    https://rahulrsingh09.github.io/AngularConcepts

  • 1

    你有几个选择:

    1 - 在等待数据时显示加载程序,使用 *ngIf 并在实际使用时显示模板的位 .

    2 - 使用BehaviourSubject并将其传递给初始占位符值,同时等待实际值 .

    3 - 在组件的模板中使用异步管道,如下所示: *ngIf="mySubject | async"

相关问题